【发布时间】:2020-01-14 20:30:45
【问题描述】:
当我调用“InitAnimation”函数时,我传递了我的对象 RG 的地址。当我分配该对象的“animationName”字段时,我可以成功打印该字段。 但是当我返回 main 并调用函数“ReportAnimation”时,我无法打印该值并且我的程序崩溃了? 为什么当我分配了该 objects 字段时,它并没有全局更改,而是仅在本地函数中更改?
我也尝试为 animationName 字段分配内存,但这不起作用。
struct Frame {
char* frameName;
struct Frame* pNext;
};
typedef struct {
char* animationName;
struct Frame* frames;
}Animation;
int main(void) {
char response;
BOOL RUNNING = TRUE;
Animation RG;
InitAnimation(&RG);
while (RUNNING) {
printf("MENU\n Enter 1 to ReportAnimation\n");
scanf("%c", &response);
switch (response) {
case '1':InsertFrame(&RG);
break;
}
}
return 0;
}
void InitAnimation(Animation* pointer) {
pointer = (Animation*)malloc(sizeof(Animation));
char* input;
input = (char*)malloc(sizeof(input));
printf("Please enter the Animation name:");
fgets(input, 32, stdin);
//pointer->animationName = (char*)malloc(sizeof(char)*10);
//Setting animation name
pointer->animationName = input;
//This print function works
printf("\nThe name is %s", pointer->animationName);
}
void ReportAnimation(Animation* pointer) {
//This print function does not work
printf("Animation name is %s\n", pointer->animationName);
}
我希望 initAnimation 函数改变 Animation 结构的字段 我希望 reportAnimation 函数打印出该字段,证明它已更改
【问题讨论】:
-
在
InitAnimation中,pointer已经指向来自调用者的Animation变量,因此pointer = malloc(sizeof(Animation));是多余的、错误的,并且存在内存泄漏。此外,input = malloc(sizeof(input));将分配一个指针大小的内存块(可能是 4 或 8 个字节长),这可能不是您想要的大小,因为您将大小 32 传递给了fgets。
标签: c pointers struct malloc function-pointers