重新分配内存并在C中重新分配的内存空间中添加字符串

时间:2014-11-29 09:11:53

标签: c memory-management dynamic realloc

我在动态分配的字符串数组末尾添加“记录”时遇到问题。在为要添加的记录重新分配更多内存之前,一切正常,然后我基本上复制了我最初的做法,但现在使用realloc。在我完成输入添加的记录后,我收到错误,我不知道如何添加记录。注意*构成的代码实际上是从原始代码中删除的。我已经尝试过很多东西,但无济于事,谢谢你提前得到的所有帮助。

#include <stdio.h>
#include <stdlib.h>
#define STRINGSIZE 21

void addRecords( char **Names, int classSize);

int main(){
    char **Names;
    int classSize, i;

    //User will be able to choose how many records he woudld like to input.
    printf("Please indicate number of records you want to enter:\n");
    scanf("%d", &classSize);

    Names=malloc(classSize*sizeof(char*));

    for (i=0; i<classSize; i++) {
        Names[i]=malloc(STRINGSIZE*sizeof(char));
    }
    printf("Please input records of students (enter a new line after each record), with following format: first name....\n");

    for (i=0; i<classSize; i++) {
        scanf("%s", *(Names + i));
    }

    for (i=0; i<classSize; i++) {
        printf("%s ", *(Names+i));                
        printf("\n\n");
    }

addRecords(Names, classSize);
}

void addRecords(char **Names, int classSize){
    int addition, i;

    printf("How many records would you like to add?\n");
    scanf("%d", &addition);

    Names=realloc(Names, (classSize+addition)*sizeof(char*));

    for (i=classSize; i<(classSize+addition); i++) {
        Names[i]=malloc(STRINGSIZE*sizeof(char));
    }

    printf("Please input records of students (enter a new line after each record), with followingformat: first name....\n");

    for (i=classSize; i<classSize+addition; i++) {
        scanf("%s", *(Names + (classSize + i)));
    }
    printf("\n\n");
    for (i=0; i<classSize+addition; i++) {
        printf("%s ", *(Names+i));
    }

    printf("\n\n");
}

2 个答案:

答案 0 :(得分:2)

你正在写出数组的界限:

for (i=classSize; i<classSize+addition; i++) {
    scanf("%s", *(Names + (classSize + i)));

更改为

for (i=classSize; i<classSize+addition; i++) {
    scanf("%s", *(Names + i));

请注意,Names[i]*(Names + i)

更具可读性

答案 1 :(得分:2)

首先,您的Names参数按值传递给addRecords函数,因此您将无法观察到它之外的重新分配(如果重新分配没有给您一个新地址,它可能会起作用,但总的来说它确实如此)。

其次,addRecords中的循环包含错误。您从classeSize循环到classSize+addition,然后在(Names + (classSize+i))中使用它。这应该是从0循环到addition或将其用作Names + i