我有这个结构:
typedef struct SM_DB { LIST_TYPE link; char name[SM_NAME_SIZE]; } SM_DB_TYPE;
我想为其’name’分配一个字符串.我是这样做的:
SM_DB_TYPE one; one.name = "Alpha";
但是,编译后我得到一个错误:“错误C2106:’=’:左操作数必须是l值”.我希望这是相当明显的.有谁知道我做错了什么?
谢谢
解决方法
假设SM_NAME_SIZE足够大,你可以像这样使用strcpy:
strcpy(one.name,“Alpha”);
只需确保你的目标有足够的空间来保存字符串,然后再进行strcpy你将得到一个缓冲区溢出.
如果你想安全地玩,你可以做到
if(!(one.name = malloc(strlen("Alpha") + 1))) //+1 is to make room for the NULL char that terminates C strings { //allocation Failed } strcpy(one.name,"Alpha"); //note that '\0' is not included with Alpha,it is handled by strcpy //do whatever with one.name free(one.name) //release space prevIoUsly allocated
如果使用malloc,请确保释放one.name,这样就不会浪费内存.