c - realloc 删除 C 数组中已有的数据

标签 c arrays calloc

出于某种原因,当我重新分配使用 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/

相关文章:

c - 使用 __builtin_popcount 或其他内在函数来处理 _mm256_movemask_pd 比较位图的结果?

php - 使用 PHP 从 JSON 更新 MySQL 表

android - 使用 xml 引用字符串数组资源中的字符串

c - 使用函数 malloc() 和 free(),初始化指针的问题

将数字字符串转换为数字

c++ - 临界区段错误 - 避免死锁

c - 如何使用 fseek() 将文件指针移动到特定位置?

PHP 和(太多)输入字段

c++ - calloc 比 malloc 好吗?

c - 在 C 中使用 calloc 初始化 int 数组,但没有接收到清零缓冲区