gpt4 book ai didi

c - VS 2010 中 realloc 的奇怪错误

转载 作者:太空宇宙 更新时间:2023-11-04 01:40:42 25 4
gpt4 key购买 nike

我有一个代码:

#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <string.h>

typedef struct NOTE
{
char NAME[50],
TELE[30];
int BDAY[3];
} NOTE;

void AddNote(NOTE * Notes, int NotesCount, NOTE * Temp)
{
Notes = (struct NOTE *) realloc(Notes, (NotesCount + 1) * sizeof(struct NOTE));
memcpy(Notes + NotesCount, Temp, sizeof(struct NOTE));
}

void main()
{
int NotesCount = 0, i = 0, f = 0;
int a;
NOTE * BLOC_NOTE, * Temp;

Temp = (struct NOTE *) malloc(sizeof(struct NOTE));
BLOC_NOTE = (struct NOTE *) calloc(0, sizeof(struct NOTE));

for(i = 0; i < 4; i++)
{
ShowInputDialog(Temp);
AddNote(BLOC_NOTE, NotesCount++, Temp);
}
}

在 BLOC_NOTE 的第三个元素上,程序崩溃在

Notes = (struct NOTE *) realloc(Notes, (NotesCount + 1) * sizeof(struct NOTE));

VS 告诉我 OS Windows 启动了一个断点...

怎么了?

编辑
把评论里的代码移到这里

void ShowInputDialog(NOTE * Temp) 
{
printf("Name: ");
scanf("%s", (*Temp).NAME);
printf("Telephone: ");
scanf("%s", (*Temp).TELE);
printf("Birthday: ");
scanf("%d\.%d\.\%d", (*Temp).BDAY, ((*Temp).BDAY + 1), ((*Temp).BDAY + 2));
}

最佳答案

这是错误的:

void AddNote(NOTE * Notes, int NotesCount, NOTE * Temp)
{
Notes = (struct NOTE *) realloc(Notes, (NotesCount + 1) * sizeof(struct NOTE));
memcpy(Notes + NotesCount, Temp, sizeof(struct NOTE));
}

Notes 是保存第一个 NOTE 对象地址的局部变量。但是当函数返回时,那个值就丢失了。您必须返回新值,因为 C 没有引用:

NOTE* AddNote(NOTE * Notes, int NotesCount, NOTE * Temp)
{
Notes = (struct NOTE *) realloc(Notes, (NotesCount + 1) * sizeof(struct NOTE));
memcpy(Notes + NotesCount, Temp, sizeof(struct NOTE));
return Notes;
}

for(i = 0; i < 4; i++)
{
ShowInputDialog(Temp);
BLOC_NOTE = AddNote(BLOC_NOTE, NotesCount++, Temp);
}

在 C++ 中这就足够了:

void AddNote(NOTE * &Notes, int NotesCount, NOTE * Temp)
{
Notes = (struct NOTE *) realloc(Notes, (NotesCount + 1) * sizeof(struct NOTE));
memcpy(Notes + NotesCount, Temp, sizeof(struct NOTE));
}

关于c - VS 2010 中 realloc 的奇怪错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6003427/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com