【问题标题】:Getting an error in the second call of the same print function in C在 C 中第二次调用相同的打印函数时出错
【发布时间】:2015-01-28 07:09:47
【问题描述】:

我试图在添加到原始记录数量后打印记录,并且我在 addRecords 函数中成功地这样做了,但在函数之外我有一个错误,但我知道如何。我通过指针传递 Names 数组,classSize 变量是全局的。所以我不明白为什么它在 addRecords 函数中起作用,而不是在 main 函数中起作用。感谢所有帮助,在此先感谢。

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

#define STRINGSIZE 21
int classSize;
void addRecords( char **Names);

int main() {
    char **Names;
    int 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);

    printf("SECOND PRINT\n\n");

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

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

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

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

    for (i = temp; i < (classSize); 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=temp; i<classSize; i++) {
        scanf("%s", *(Names +i));
    }
    printf("\n\n");
    printf("FIRST PRINT\n\n");

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

    printf("\n\n");
}

【问题讨论】:

  • @2501 我搞砸了将 Names 设置为全局变量,老实说,我不知道如何通过引用传递它。有什么建议吗?
  • 你遇到了什么错误?
  • 第二个打印调用正在查看一个空的内存空间,我试图弄清楚如何使 addRecords 函数中的 realloc 成为全局的。 @rpattiso
  • @kenshin Jean-Baptiste Yunès 回答您的other question 回答了这个问题。您需要将return Names 添加到addRecords 并更新其返回类型,并在main 中以Names = addRecords(Names) 进行调用。

标签: c dynamic scope printf


【解决方案1】:

C 使用按值传递。 addRecords 内的 Namesmain 内的 Names 是不同的变量。调用该函数时会创建一个副本。

要解决此问题,您需要通过引用传递 Names,或者将其设为全局变量,或者通过函数返回值返回更新后的副本。

在您的实际代码中,在将main() 传递给函数中的realloc 之后尝试在main() 中使用Names,会导致未定义的行为(realloc 使其参数不确定)。

【讨论】:

  • 我明白了,感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-06-23
  • 2020-01-29
  • 1970-01-01
  • 2018-05-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多