当我调用“InitAnimation”函数时,我传递了对象 RG 的地址。当我分配该对象的“animationName”字段时,我可以成功打印该字段。 但是当我返回主函数并调用函数“ReportAnimation”时,我无法打印该值并且我的程序崩溃了? 为什么当我分配该对象字段时,它不会全局更改,而仅在本地函数中更改?
我也尝试过为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 函数打印出该字段,证明其已更改
最佳答案
更改函数变量的值(包括声明为参数的变量)对调用者没有影响。
void bad1(int i) {
i = 1; // No effect on the caller.
}
void bad2(void* p) {
p = NULL; // No effect on the caller.
}
如果您想更改调用者中的变量,则需要传递一个指向它的指针。
void good1(int* i_ptr) {
*i_ptr = 1;
}
void good2(void** p_ptr) {
*p_ptr = NULL;
}
因此,要么将指针传递给指针,要么将指针传递给已分配的结构。你可以使用
Animation ani;
Animation_init(&ani, name);
...
Frame* frame = Frame_new(name);
Animation_append_frame(&ani, frame);
...
Animation_destroy(&ani);
或
Animation* ani = Animation_new(name);
...
Frame* frame = Frame_new(name);
Animation_append_frame(ani, frame);
...
Animation_delete(ani);
假设你有
typedef struct Frame {
char* name;
struct Frame* next;
} Frame;
typedef struct {
char* name;
Frame* first_frame;
Frame* last_frame;
} Animation;
void Animation_init(Animation* self, const char* name) {
self->name = strdup(name);
self->first_frame = NULL;
self->last_frame = NULL;
}
void Animation_destroy(Animation* self) {
Frame* head = self->first_frame;
while (head != NULL) {
Frame* next = head->next;
Frame_delete(head);
head = next;
}
free(self->name);
}
Animation* Animation_new(const char* name) {
Animation* self = malloc(sizeof(Animation));
Animation_init(self, name);
return self;
}
void Animation_delete(Animation* self) {
Animation_destroy(self);
free(self);
}
void Animation_append_frame(Animation* self, Frame* frame) {
if (self->last_frame == NULL) {
self->first_frame = frame;
} else {
self->last_frame->next = frame;
}
while (frame->next != NULL)
frame = frame->next;
self->last_frame = frame;
}
关于用指针调用函数不会改变该指针的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57915576/