[英]How do declare array of pointer to struct in C and then use it?
我的目的是声明一个指向我的人结构的指针数组,然后使用它来修改人的名字和年龄。我在代码中很迷失,因此将不胜感激。谢谢!
#include <stdio.h>
#define HOW_MANY 7
char *names[HOW_MANY]= {"p1", "p2", "p3", "p4", "p5", "p6", "p7"};
int ages[HOW_MANY]= {2, 1, 16, 8, 10, 3, 4};
struct person
{
char person_name[30];
int person_age;
}*array[10];
static void insert(struct person array[], char *name, int age)
{
static int nextfreeplace = 0;
array[nextfreeplace] = (struct person*) malloc(sizeof(struct person));
&array[nextfreeplace]->person_name = name;
&array[nextfreeplace]->person_age = age;
nextfreeplace++;
}
int main(int argc, char **argv)
{
struct person *array[10];
int index;
int personNumber = 1;
for (index = 0; index < HOW_MANY; index++)
{
insert (array[index], names[index], ages[index]);
}
for (index = 0; index < HOW_MANY; index++)
{
printf("\nPerson number %d has name %s and age %d \n", personNumber,
array[index]->person_name, array[index]->person_age);
personNumber++;
}
return 0;
}
我得到的错误:
arrays.c: In function ‘insert’:
arrays.c:20: warning: implicit declaration of function ‘malloc’
arrays.c:20: warning: incompatible implicit declaration of built-in
function ‘malloc’
arrays.c:20: error: incompatible types when assigning to type
‘struct person’ from type ‘struct person *’
arrays.c:21: error: invalid type argument of ‘->’ (have ‘struct person’)
arrays.c:22: error: invalid type argument of ‘->’ (have ‘struct person’)
make: *** [arrays] Error 1
您已在此处成功声明了指向您的结构的指针数组
struct person *array[10];
然后,您需要分配内存,以便该数组中的每个指针实际上都指向您的结构的实例
目前您通过
array[index]
insert
作为第一个参数,但array[index]
类型为person*
但您的insert
函数需要person []
。
您尝试在insert
函数中访问array[nextfreeplace]
,但是当您传递一个person*
进行insert
这将尝试读取一个可能无效的内存地址,因为
array[nextfreeplace] = (struct person*) malloc(sizeof(struct person));
与...相同
*(array + nextfreeplace) = (struct person*) malloc(sizeof(struct person));
因此,只要nextfreeplace
不为零,您就在有效地尝试分配动态内存,并将指向它的指针存储在不应使用的地址上。
这导致潜在的不确定行为。 您不能像对待数组本身一样对待array
内部的指针(除非您分配足够的内存并将其视为此类-代码中不是这种情况)。 您当然可以将malloc
的返回值存储到此指针某个偏移处的地址。 就您的代码而言,每个array[index]
都不是您可以自由读取和写入的数组,并且在没有出现问题的情况下不应将其视为此类数组。
您可以考虑将insert
更改为
void insert(struct person** p, char *name, int age)
{
*p = malloc(sizeof(struct person));
}
然后将main
循环更改为
for (index = 0; index < HOW_MANY; index++)
{
insert (&array[index], names[index], ages[index]);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.