如何将字符串保存到结构数组成员?

时间:2016-08-20 20:50:56

标签: c

我正在尝试将数组[0]上的字符串保存到人员[0] .name但是我收到此错误:使用数组类型赋值给表达式。我该怎么办?

#include <stdio.h>
#include <stdlib.h>
struct person{
    char name[25];
};
int main(){
    struct person persons[10];
    int i=0;
    int array[10];
    char str[] ="This is a test";
    char * pch;

    printf ("Splitting string \"%s\" into tokens:\n",str);
    pch = strtok (str," ");
    while (pch != NULL)
    {
      array[i]=pch;
      pch = strtok (NULL, " ");
      i++;
    }
   //persons[0].name=array[0]; //error: assignment to expression with array type
   printf("persons.name: %s\n", persons[0].name);
   printf("array[0] = %s", array[0]);
}

1 个答案:

答案 0 :(得分:-2)

尝试strcpy而不是使用=分配值:

strcpy(persons[0].name, array[0])