简体   繁体   English

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

[英]copy a struct array to another (not struct) array in C

I am trying to copy name array to another array and print it我正在尝试将名称数组复制到另一个数组并打印它

#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;
}

But it gives me an error:但它给了我一个错误:

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

How do I fix this?我该如何解决?

You can change:你可以改变:

char new_array[100];

to:至:

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

Then using strcpy to copy string in c.然后使用strcpy复制 c 中的字符串。 If you want to calculate the number of elements of array, using:如果要计算数组的元素数,请使用:

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

Then, the for loop becomes:那么,for循环就变成了:

for(int i =0; i < sizeof(people)/sizeof(people[0]); i++) {
        strcpy(new_array[i],people[i].name);
        printf("%s ", new_array[i]);
}

You are trying to assign a string to a char which is described by your error.您正在尝试将字符串分配给错误描述的字符 To copy a string to a char array, you should use strcpy() .要将字符串复制到 char 数组,您应该使用strcpy()

Also, your new_array is a mere array of characters and has no way to differentiate two different names.此外,您的new_array只是一个字符数组,无法区分两个不同的名称。

To make it an array of strings, you should use a 2D array where you can index the row to get different strings like below要使其成为字符串数组,您应该使用二维数组,您可以在其中索引行以获取不同的字符串,如下所示

char new_array[10][100]

This makes an array of 10 strings of 100 characters each.这将创建一个由 10 个字符串组成的数组,每个字符串包含 100 个字符。

Also, your iteration over the array of structure is messy.此外,您对结构数组的迭代很混乱。

To get correct size of array of structure, you should use要获得正确大小的结构数组,您应该使用

int size = sizeof(people)/sizeof(people[0])

So, your final code becomes-因此,您的最终代码变为-

#include <stdio.h>
#include <string.h>

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

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

    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM