gpt4 book ai didi

c - 使用 realloc 将元素添加到数组

转载 作者:行者123 更新时间:2023-11-30 17:55:33 24 4
gpt4 key购买 nike

我试图在输入字符后使用 realloc 将元素添加到数组中。这是我的代码:

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

int main(void)
{
int i, j, k;
int a = 1;
int* array = (int*) malloc(sizeof(int) * a);
int* temp;
for(i = 0;;i++)
{
scanf("%d", &j);
temp = realloc(array, (a + 1) * sizeof(int));
temp[i] = j;
if(getchar())
break;
}
for(k=0; k <= a; k++)
{
printf("%d", temp[k]);
}
}

当我运行这个小程序时,如果我输入例如:2 3 4它显示我:20;我知道内存没有正确分配,但我无法找出问题所在。提前致谢。

最佳答案

首先:

    int* array = (int*) malloc(sizeof(int) * a);
int* temp = array;

    temp = realloc(temp, (a + 1) * sizeof(int));

因为在调用“realloc”之后,作为第一个参数传递的指针可能会变得无效。

当然,调用“realloc”时第二个参数始终等于 2。

顺便说一下,“scanf”在第一个非数字字符后停止读取您的输入字符串。阅读文档以正确使用函数。例如关于 scanf()realloc() .

关于c - 使用 realloc 将元素添加到数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14206184/

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