gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 06:25:47 25 4
gpt4 key购买 nike

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

最佳答案

你正在写出数组的边界:

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) 更具可读性>

关于c - 重新分配内存并在 C 中重新分配的内存空间添加一个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27200661/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com