【发布时间】:2016-10-24 14:45:33
【问题描述】:
在下面的程序中,我试图通过调用 malloc() 来创建函数 insert() 来分配内存以创建一个新的结构(人)...但是我收到以下警告:分配来自不兼容的指针类型 [启用默认情况下]...我应该如何使用 malloc() 函数?
#include <stdio.h>
/* these arrays are just used to give the parameters to 'insert',
to create the 'people' array
*/
#define HOW_MANY 7
char *names[HOW_MANY]= {"Simon", "Suzie", "Alfred", "Chip", "John", "Tim",
"Harriet"};
int ages[HOW_MANY]= {22, 24, 106, 6, 18, 32, 24};
typedef struct
{
char *name;
int age;
}person;
static void insert(person *p, char *name, int age)
{
p = (struct person *)malloc(sizeof(person));
p->name = name;
p->age = age;
}
int main(int argc, char **argv)
{
person people[7];
for (int i = 0; i < 7; i++)
{
insert (&people[i], names[i], ages[i]);
}
for (int i = 0; i < 7; i++)
{
printf ("name: %s, age: %i\n", people[i].name, people[i].age);
}
return 0;
}
【问题讨论】:
-
struct person和person不一样。第一个甚至不存在 -
@roderickyoung 当然,我的也不见了。 :)
标签: c pointers malloc dynamic-memory-allocation