1.char test[20]="xxxxx";编译是不会出错的。
2.struct student
{
int num;
char name[20];
float score[3];
};
void main(int argc, char* argv[])
{
struct student stu;
stu.name="xxxxx";
}
会报:
error C2440: '=' : cannot convert from 'char [6]' to 'char [20]'
There is no context in which this conversion is possible
这样的错误。
3.改成struct student
{
int num;
char name[6];
float score[3];
};
void main(int argc, char* argv[])
{
struct student stu;
stu.name="xxxxx";
}
则会报:
error C2106: '=' : left operand must be l-value
4.将char name[20];改为char *name;就不会报错了。
请问上面为什么报错?
1.数组在定义时可以用字符串对其直接初始化,如你程序中:
char test[20]="xxxxx";
这是编译不报错的原因。
2.若要对数组进行赋值可用strcpy或者对数组每个元素单独赋值。你程序中:
stu.name="xxxxx";
赋值运算符左边stu.name是个地址常量,显然是不能被赋值的,编译肯定是要报错的。