编译器给警告在第55行(BOLD):指向不同的对象。怎么样数组字符串的转换?这是对的吗?接收到的字符串应该用绳子可用阵列比较..
解决方案创建一个包含字符串数组,像
字符富[] =酒吧;它实际上是一样以下
字符富[] = {'B','A','R','\\ 0'};或以下
为const char *富=酒吧;这个变量,富可以使用,也可以作为一个数组(即第二个字母是 foo的[1] ),或者可以传递给函数的指针(如的strlen(富)将返回3)。
因此,从程序的角度来看,一个字符数组或字符指针是等价的,与你不能分配给一个字符数组,但你可以分配给指针异常。所以以下是好的:
字符富[] =酒吧;字符* PFOO = foo的;但是,这是不行的:
为const char * PFOO =酒吧;字符富[] = PFOO; / *错误! * /还有另外一件事那就是字符数组和字符指针之间的不同:一个字符数组的使用的sizeof 运算符返回数组中的字符数(包括终止零),但在一个字符指针它返回指针的大小
例如:
字符富[] =富;为const char *巴=酒吧;的printf(的sizeof(富)=%lu个\\ N的sizeof(富));的printf(strlen的(富)=%lu个\\ N,strlen的(富));的printf(的sizeof(巴)=%lu个\\ N的sizeof(巴));的printf(strlen的(巴)=%lu个\\ N的strlen(巴));如果您运行在64位机器上上述code(其中三分球是八个字节),它将打印:
的sizeof(富)= 4strlen的(富)= 3的sizeof(巴)= 8strlen的(巴)= 3`#include<reg51.h> #include<string.h> #include"_LCD_R8C.c" unsigned char c[11]; void serial_int (void) interrupt 4 { static unsigned char chr[11]; int i,j; if (RI==1) { RI = 0; TI = 0; chr[11] = SBUF; for(j=0;j<1;j++) { for(i=0;i<=10;i++) { c[i]=chr; } c[11]='\0'; } } }int main() { unsigned char a[2][11]={"$0016221826","$0123456789"}; int i,j; lcd_init(); lcd_clear(); SCON = 0x50; TMOD = 0x20; TH1 = 0xFD; ET0 = 0; TR1 = 1; RI = 1; ES = 1; EA = 1; for(i=0;i<=1;i++) { **j=strcmp(a,c);** if(j==0) { lcd_printxy(1,1,"yes"); } else { lcd_printxy(1,6,"no"); } } }`
the compiler is giving warning in line 55(BOLD): pointer to different objects. how about array to string conversion? is it correct? the received string should compare with the available array of strings..
解决方案Creating an array that contains a string, like
char foo[] = "bar";it's actually the same as the following
char foo[] = { 'b', 'a', 'r', '\0' };or the following
const char *foo = "bar";This variable, foo can be used either as an array (i.e. the second letter is foo[1]) or as a pointer that can be passed to a function (like strlen(foo) will return 3).
So from the point of your program, a character array or a character pointer are equivalent, with the exception that you can't assign to a character array but you can assign to the pointer. So the following is okay:
char foo[] = "bar"; char *pfoo = foo;But this is not okay:
const char *pfoo = "bar"; char foo[] = pfoo; /* Error! */There is also another thing that is different between character arrays and character pointers: Using the sizeof operator on a character array returns the number of characters in the array (including the terminating zero), but on a character pointer it returns the size of the pointer.
Example:
char foo[] = "foo"; const char *bar = "bar"; printf("sizeof(foo) = %lu\n", sizeof(foo)); printf("strlen(foo) = %lu\n", strlen(foo)); printf("sizeof(bar) = %lu\n", sizeof(bar)); printf("strlen(bar) = %lu\n", strlen(bar));If you run the above code on a 64-bit machine (where pointers are eight bytes), it will print:
sizeof(foo) = 4 strlen(foo) = 3 sizeof(bar) = 8 strlen(bar) = 3
更多推荐
数组字符串转换
发布评论