【发布时间】: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