将一个结构数组复制到C中的另一个(不是结构)数组

问题描述 投票:0回答:1

我正在尝试将名称数组复制到另一个数组并打印它

#include <stdio.h>

typedef struct 
{
    char name[100];
    int age;
} data; 

int main() {
    char new_array[100];
    data people[] = {{ "john", 12},{" kate", 15}};
    for(int i =0; i < sizeof(people); i++) {
        new_array[i] = people[i].name;
        printf("%c ", new_array[i]);
    }

    return 0;
}

但是它给我一个错误:

error: assignment to ‘char’ from ‘char *’ makes integer from pointer without a cast [-Werror=int-conversion]
     new_array[i] = people[i].name;
                  ^

我该如何解决?

c arrays
1个回答
2
投票

您可以更改:

char new_array[100];

至:

char new_array[10][100]; // for maximum 10 strings

然后使用strcpy复制c中的字符串。如果要计算数组元素的数量,请使用:

sizeof(people)/sizeof(people[0]);

然后,for循环变为:

for(int i =0; i < sizeof(people)/sizeof(people[0]); i++) {
        strcpy(new_array[i],people[i].name);
        printf("%s ", new_array[i]);
}
© www.soinside.com 2019 - 2024. All rights reserved.