如何设置结构的字符串属性? [英] How do I set a string property of a struct?
本文介绍了如何设置结构的字符串属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的代码如下:
#include <stdio.h>
struct MyData {
int id;
char msg[255];
};
int main ( int argc, const char * argv[] ) {
struct MyData item;
item.id = 3;
item.msg = "something else";
printf("Msg: %d", item.msg);
return 0;
}
我在线上的赋值中收到类型不兼容的错误:item.msg = "别的东西";
I get an error of incompatible types in assignment on the line: item.msg = "something else";
我不用担心设置 id 属性,但我不知道如何设置字符串属性msg".知道我做错了什么吗?
I have no worries setting the id property, but I can't figure out how to set the string property "msg". Any ideas what I'm doing wrong ?
推荐答案
使用 strncpy()
将字符串复制到字符缓冲区中.不要忘记将 \0
分配给最后一个元素以防万一.
Use strncpy()
to copy the string into the character buffer. Don't forget to assign \0
to the last element just in case.
这篇关于如何设置结构的字符串属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文