在下面的程序,我试图使功能插件()调用malloc()
创建一个新的结构(人)来分配内存...但我得到以下警告:从分配不兼容指针类型[默认情况下启用] ...我应该如何使用malloc()函数?使用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;
}
'结构person'和'person'是不一样的。第一个不存在 – ForceBru
[请参阅此讨论,为什么不在'C'中为malloc()'和family生成返回值。](http://stackoverflow.com/q/605845/2173917 )。 –
@roderickyoung当然,我的也走了。 :) –