我创建了一个由char *name
组成的Human数组。
我使用这样的功能:
Human *createHuman(char *name){
Human *h = malloc(sizeof(Human));
h->name = strdup(name);
return h;
}
我已经测试了此功能,它可以正常工作,但是当我这样使用它时,我的问题就开始了:
void gen_Humans(Human array[MAX], int n){
//n == max;
for (int i = 0; i<n; i++){
char *name = gen_name_function_used_before_WORKING();
array[i] = *createHuman(*name);
}
…
}
正如我所说,如果我产生一个人,那就很好。
我调试了代码,到了strdup(name)
的地步,这让我感到震惊:
my error: Exception thrown at 0x53DCF6E0 (ucrtbased.dll) in project.exe:
0xC0000005: Access violation reading location 0x00000070.
我正在使用VS 2017 Enterprise。
答案 0 :(得分:1)
在调用函数createHuman
时,您正在传递名称的值:
array[i] = *createHuman(*name);
在构建此应用程序时,Iam收到以下编译器警告(GCC):
warning: passing argument 1 of 'createHuman' makes pointer from integer without a cast
由于您的函数createHuman
需要使用该名称的地址,因此您也应该传递地址。例如:
array[i] = *createHuman(name);
答案 1 :(得分:1)
添加到@MortizSchmidt的答案:
git reset --hard
的结果。即使失败的机会很小,您也应该这样做。malloc()
ed的内存,也没有将指针放在任何地方。请记住,C与Java不一样-赋值不是引用的赋值。malloc()
指示符没有任何作用。该参数可以通过任何形式编写为int *:MAX
,int* array
或int array[]
。实际上,为什么还要分配Human结构而不是仅仅为字符串分配空间?
int array[MAX]
这具有将struct Human createHuman(char *name){
if (name == NULL) {
struct Human h = { NULL };
return h;
}
struct Human h = { strdup(name) };
if (h.name == NULL) { /* handle error here */ }
return h;
}
void gen_Humans(Human array[MAX], int n){
for (int i = 0; i < n; i++) {
char *name = gen_name_function_used_before_WORKING();
array[i] = createHuman(name);
}
…
}
初始化为0之后将Human
中的所有字段初始化的额外好处。