c - 如何初始化包含数组的结构

标签 c arrays initialization structure

#include <stdio.h>

struct Name {char d[11]};

int main (){

  char str[11];
  scanf("%s",str);

  struct Name new = {str};
}

我想初始化 Name 结构体,但是有一个警告:suggest braces around initialization of subobject。

如何将读取的字符数组放入我的 Name 结构中?

最佳答案

有两种方式:

int main ()
{
  char str[11];
  scanf("%10s",str); // Make sure you don't read more than 
                     // what the array can hold.

  struct Name name1 = {"name"}; // This works only if you use string literal.
  struct Name name2;
  strcpy(name2.d, str);         // Use this when you want to copy from another variable.
}

关于c - 如何初始化包含数组的结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28843360/

相关文章:

android - android中的地址路径

python - Python方式为一维数组中的每个元素在第三维创建新的二维数组

.net - 在调用基类型构造函数之前,是否可以强制 VB.NET 初始化实例变量?

c# - 无法从 double[][] 转换为 double[*,*]

javascript - (Un)通过字符串输入设置嵌套数组值

http - GAE Go,init() - 多次调用它?

c++ - 0 C++ 内置类型的初始化

c - 尝试找出在为数组分配的堆内存中分配值期间的错误

c - switch 和 if 语句顺序(机器人 C)

c - 启用 linux 服务以显示弹出窗口