有关字串的问题

来源:百度知道 编辑:UC知道 时间:2024/05/18 02:31:17
void main(void)
{
char name[30];
name="asdf";
}
编译报错:
Compiling...
Test.cpp
e:\VCProgram\Learn\Test\Test.cpp(8) : error C2440: '=' : cannot convert from 'char [5]' to 'char [30]'
There is no context in which this conversion is possible
Error executing cl.exe.

Test.exe - 1 error(s), 0 warning(s)
其中:
cannot convert from 'char [5]' to 'char [30]'
是什么原因?怎么解决啊?

你定义了一个长度为30的字符数组name,要给它赋值成"asdf"是不可以的,这种赋值只能在初始化的时候进行,如果之后再赋值要用strcpy函数,或者一个字符一个字符的进行

void main(void)
{
char name[30]="asdf";
}

或者
#include "string.h"
void main(void)
{
char name[30];
strcpy(name,"asdf");
}
都可以

字符串不能直接赋值,要用字符串拷贝:
strncpy( name, "asdf", sizeof( name ) );

老兄有个问题,你可能没有搞清楚.
char name[30] 其中 name 是一个char 型的指针.

注意,他是常量,是不能在重新赋值的...

如同 name++;等操作都是错的.

f