我试图编写一个函数realloc 3数组,这些数组是使用malloc在main中创建的,但每次我尝试运行程序时,都会出现错误并且程序停止工作。
在我尝试调试时,我尝试在" realloc"之后打印数组。并且看起来realloc已成功完成但在我扫描到那些新记录后,当我要打印时,我收到错误。
更正1:按照建议更正了scanf行中的错误。一旦输入第一个新记录,程序就会出错
感谢所有投入!
void addRecord(char** firstName,char** lastName, float* score, int * recordSize)
{
int add,i;
printf("How many records do you want to add? ");
scanf("%d", &add);
firstName = realloc(firstName, (*recordSize+add)*sizeof(char*));
for (i=*recordSize; i<(*recordSize)+add; i++)
firstName[i]= malloc(STRSIZE*sizeof(char));
lastName = realloc(lastName, (*recordSize+add)*sizeof(char*));
for (i=*recordSize; i<(*recordSize)+add; i++)
lastName[i]= malloc(STRSIZE*sizeof(char));
score = realloc(score, (*recordSize+add)*sizeof(float));
printf("Please enter the record to be added: \n");
printf("FirstName LastName Score\n");
for (i=*recordSize; i<*recordSize+add; i++)
scanf("%s %s %f", firstName[i], lastName[i], &score[i]);
*recordSize +=add;
}
答案 0 :(得分:0)
您应该知道,如果指针地址发生变化,您的主要功能将无法显示您的重新分配。您正在重新分配整个字符串数组,但此更改仅发生在addRecord()
函数中。当您返回主函数时,可能会有dangling pointer,因为realloc()
可以返回新的内存地址并释放原始内存块。这是printf("%p\n", firstName);
可以在addRecord()
中打印不同的内容,并在addRecord()
之后返回主函数。
例如:
#include <stdio.h>
/* Simulate the reallocation of bar by swapping oldbar and bar. */
void foo(int *bar)
{
static int *oldbar = NULL;
if (oldbar == NULL) {
oldbar = bar;
bar = NULL;
} else {
bar = oldbar;
oldbar = NULL;
}
printf("bar after reallocating is: %p\n", (void *)bar);
}
/* Notice the extra * below and the dereferencing of the pointer, allowing
main() to see the change. */
void foo_works(int **bar)
{
static int *oldbar = NULL;
if (oldbar == NULL) {
oldbar = *bar;
*bar = NULL;
} else {
*bar = oldbar;
oldbar = NULL;
}
printf("bar after reallocating is: %p\n", (void *)bar);
}
int main(void)
{
int bar[] = {1, 1, 2, 3, 5, 8};
int *barptr = bar;
printf("barptr before reallocating is: %p\n", (void *)barptr);
foo(barptr);
printf("barptr after reallocating is: %p\n\n", (void *)barptr);
printf("barptr before reallocating is: %p\n", (void *)barptr);
foo_works(&barptr);
printf("barptr after reallocating is: %p\n", (void *)barptr);
}
对于字符串数组,您只需要在*
的定义中添加另一个foo_works()
参数和解除引用。这样你就有了一个指向数组的指针,它允许你的主函数可以看到更改。当然,这意味着您将成为Three Star Programmer,您可能会考虑重构使用结构来代替您的记录......