how to pass strings to char array in C
char array[2];
array = "h";
Gives the following error:
error: incompatible types when assigning to type 'char[2]' from type 'char'
char array[2];
array[] = "h";
Gives the following warning:
warning: assignment makes integer from pointer without a cast
I tried these two ways to pass the value h into the array but I can't. I want to know what the problem is.
Arrays can't be pointed to a new address.
You can initialize them with a string constant:
char array[2] = "h";
or you can copy data into the array later:
char array[2];
strcpy(array, "h");
or:
array[0] = 'h';
array[1] = ' ';
If you'd used a char *
instead, your first example would work:
char *array = NULL;
array = "h";
链接地址: http://www.djcxy.com/p/28362.html
上一篇: Malloc困惑
下一篇: 如何将字符串传递给C中的char数组