【问题标题】:Reallocating memory and adding a string at the reallocated memory space in C重新分配内存并在C中重新分配的内存空间添加一个字符串
【发布时间】:2015-01-27 19:42:59
【问题描述】:

我在动态分配的字符串数组末尾添加“记录”时遇到问题。在为要添加的记录重新分配更多内存之前,一切正常,然后我基本上复制了我最初所做的,但现在使用 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");
}

【问题讨论】:

  • 请缩进您的代码。
  • I get an error .. 请告诉我们。
  • @2501 对不起,我觉得最好知道

标签: c memory-management dynamic realloc


【解决方案1】:

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

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

【讨论】:

  • 其实main中并没有声明。
  • @2501 由于缩进不好,第一次尝试,看起来是这样。
  • @Jean-BaptisteYunès 抱歉格式错误,非常感谢您的帮助。
  • 别担心,弄错了。
【解决方案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) 更具可读性

【讨论】:

  • 是的,我现在看到了。我不知道我是怎么错过的。非常感谢!
猜你喜欢
  • 2022-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-15
  • 2014-11-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多