出于某种原因,当我重新分配使用 calloc 创建的数组的大小时,它会删除已输入的值,也许发生了其他事情,但我不明白为什么。我已经更改了代码,以便它包含工作所需的所有内容,抱歉我忘记了
#include <stdio.h>
#include <stdlib.h>
int main(void) {
unsigned int arraySize; // size of array
int moreElements; // stores user input whether more elements are to be
int additionalElements = 0; // number of elements to be added to array
unsigned int type; // stores the type of array
float sum = 0; // the sum of the elements
float *floatArrPtr; // pointer to a flaot
floatArrPtr = calloc(arraySize, sizeof(float));
for(size_t i = 0; i < arraySize; i++)
{
printf("Please enter a number for the array: ");
scanf("%f", &floatArrPtr[i]);
printf("%f\n", floatArrPtr[i]);
}
for(size_t i = 0; i < arraySize; i++)
{
sum += *(floatArrPtr+i);
}
sum /= arraySize;
printf("The average of the elements of the array is %lf\n", sum);
do
{
printf("if there are more elements to be added enter 1 and 0 if not: ");
scanf("%d", &moreElements);
} while (moreElements != 0 && moreElements != 1);
if (moreElements == 1) {
printf("please enter the number of additional elements you want to add: ");
scanf("%d", &additionalElements);
floatArrPtr = realloc(intArrPtr,(arraySize+additionalElements) * sizeof(float));
for (size_t i = arraySize; i < arraySize+additionalElements; i++)
{
printf("Please enter a number for the array: ");
scanf("%f", &floatArrPtr[i]);
}
sum = 0;
for(size_t i = 0; i < arraySize+additionalElements; i++)
{
sum += *(floatArrPtr+i);
printf("%zu, %lf, %d\n", i, floatArrPtr[i], arraySize + additionalElements);
}
sum /= (arraySize + additionalElements);
printf("The average of the elements of the array is %lf\n", sum);
}
}
最佳答案
顶部的 calloc 代码是错误的。对于 1000 的 arraySize,它分配一百万个 float ,即 4MB。查一下。
然后我假设真正的问题是从早期代码中滑入的 intArrayPtr 。
使用函数,就会得到返回。 – 我的意思是让每个函数的所有代码不超过 4 行或这么长,这将阻止之前的旧变量溜进来。
错误的行是
floatArrPtr = realloc(intArrPtr...
你需要
floatArrPtr = realloc(floatArrPtr...
我不知道 intArrPtr 的用途,但看起来如果该代码编译它来自上面的代码。
你有全局变量。人们必须非常小心地对待它们,因为它们充其量是一种痛苦,最坏的情况是它们会导致不可预见的边缘情况错误,这就是您所遇到的。
将您的项目制作为两个文件,一个用于整数,一个用于浮点,您将在编译器中看到错误。
关于c - realloc 删除 C 数组中已有的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43217317/