【发布时间】: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)进行调用。