将字符串分配给 C 中结构中的元素 [英] Assign string to element in structure in C
问题描述
我有这个结构:
typedef struct SM_DB
{
LIST_TYPE link;
char name[SM_NAME_SIZE];
} SM_DB_TYPE;
我想为其名称"分配一个字符串.我是这样做的:
And I would like to assign a string to its 'name'. I am doing so like this:
SM_DB_TYPE one;
one.name = "Alpha";
但是,编译后我得到一个错误:错误 C2106:'=':左操作数必须是左值".我希望这是相当明显的.有谁知道我做错了什么?
However, after compiling I get an error: "error C2106: '=' : left operand must be l-value". I am hoping this is fairly obvious. Does anyone know what I am doing wrong?
谢谢
推荐答案
假设 SM_NAME_SIZE
足够大,你可以像这样使用 strcpy
:
Assuming SM_NAME_SIZE
is large enough you could just use strcpy
like so:
strcpy(one.name, "Alpha");
在执行 strcpy 之前,请确保您的目的地有足够的空间来容纳字符串,否则您会遇到缓冲区溢出.
Just make sure your destination has enough space to hold the string before doing strcpy your you will get a buffer overflow.
如果你想安全,你可以这样做
If you want to play it safe you could do
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
以免浪费内存.
Make sure you free one.name
if using malloc so that you don't waste memory.
这篇关于将字符串分配给 C 中结构中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!