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

How to initialize a structure that contains an array

#include <stdio.h>

struct Name {char d[11]};

int main (){

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

  struct Name new = {str};
}

我想初始化新的 Name 结构,但是有一个警告:建议在子对象的初始化周围使用大括号。

如何将读取的字符数组放入我的 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.
}

你可以这样做:

#include <stdio.h>

struct Name {char d[11];};

int main (){

  char str[11] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
  scanf("%s",str);

  // The below is C99 style.
  struct Name new = { .d = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}};
  struct Name new2 = { .d = "hi mum"};

  // Memcpy does the job as well
  memcpy(new.d, str, sizeof(str));
}

编辑:

如果您想要将 str-缓冲区中的任何内容复制到 Name,您可以像上面那样做。你也可以这样做。

struct Name new;
scanf("%s", new.d); /* Work directly on the structure. */

有关 C99 样式结构初始化的更多信息,请查看此 Whosebug 问题:C struct initialization with char array

同时注意 R. Sahu 的警告,不要读取超过数组所能容纳的内容。

在 C 中初始化结构时,最好创建一个函数来进行初始化。我通常使用名称行 init_"name of struct"。对于您的情况,一个简单的 strncpy 将初始化您的字符串字段。我使用 strncpy 来避免注销字符串的末尾。提示使用#define 来设置所有字符串的长度。稍后,当字符串长度发生变化时,您可以轻松解决问题。这是您使用初始化函数

编写的代码
#include <stdio.h>
#include <string.h>
#include <stdlib.h>


#define NAME_LEN (11)

struct Name { char d[NAME_LEN]; };

void init_name(struct Name * n, char *s); // proto types should go in a h file


void init_name(struct Name * n, char *s)
{
    strncpy(n->d, s, NAME_LEN);  // copy s to name file d
}

int main(){

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

    init_name(&newName, str);
}
given the problems with the scanf() 
given the probability of a buffer overflow/undefined behaviours, etc

I suggest using:

#include <stdio.h>

#define MAX_LEN (11)

// define the struct
struct Name {char d[MAX_LEN]};

// declare instance of the struct
struct Name myName;

int main ()
{
    // remember: char *fgets(char *str, int n, FILE *stream)
    if( fgets( myName.d, MAX_LEN, stdin ) )
    { // then fgets successful
         printf( "%s\n", myName.d);
    }
    else
    { // else, fgets failed
        printf( "fgets failed\n");
    }
    return( 0 );
} // end function: main