c - VS 2010 中 realloc 的奇怪错误

标签 c visual-studio struct realloc

我有一个代码:

#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/

相关文章:

c - "space bar"之后扫描字符终止的问题

visual-studio - Visual Studio 2015 Update 1 RC - 停止调试时崩溃

c++ - 静态库在控制台中有效,但在 GUI 应用程序中无效 - 奇怪

Asp.net core razor View 未格式化

c - 如何在没有 <graphics.h> 库的情况下设置像素?

相当于宏的 C sizeof

c - 有没有办法找出指针指向什么类型的结构?

c - 在多个文件中使用结构

c++ - 编写 if then else 类型语句的简洁方法

c++ - C++中结构/类的历史是什么?