首页 > 解决方案 > 增加数组大小。在 increaseSize 函数之后,同一数组的某些参数无效。C语言

问题描述

该程序从“numbers.txt”文件中获取一些 txt 输入。它首先计算该文本文件中所有数字的数量(freqCount),然后再次读取文件并使用 malloc 创建两个数组 A 和 B ,它们的大小都等于所有数字的数量文本文件。到目前为止,一切都很好。

现在我想增加数组 A 的大小,以便可以在其中放入更多“freqCount”参数。在我创建的 freqRepeat 函数中,有一个函数 increaseSize 采用相同的数组 A,并使用 realloc 在其中添加 2*freqCount 更多参数。

调用上面提到的函数 increaseSize 后,出现了一个问题,因为只有部分参数保持不变,而且很少有参数变成了一个巨大的数字。这是一个重大问题。谁能给我一些帮助?谢谢

附言。我在代码末尾包含了示例性文本文件输入。

#include <stdio.h>
#include <stdlib.h>
int read_ints(const char *file_name, int *result);
int *scanFreq(const char *file_name, int *A, int *B, int *resultTab);
int freqRepeat(int *A, int *B, int freqCount);
int *increaseSize(int *A, int freqCount);
void calcmalc(int freqCount);
int *nextArray(int *A, int *B, int freqCount, int freqStart);

int main()
{
  int result = 0;
  int resultTab = 0;
  int freqCount;
  freqCount = read_ints("numbers.txt", &result);
  printf("freqCount is %d", freqCount);
  int *A = (int *)malloc(freqCount * sizeof(int));
  int *B = (int *)malloc(freqCount * sizeof(int));
  scanFreq("numbers.txt", A, B, &resultTab);
  freqRepeat(A, B, freqCount);

}
int read_ints(const char *file_name, int *result)
{
  FILE *file = fopen("numbers.txt", "r");
  int i = 0;
  int n = 0; //row number//

  if (file == NULL)
  {
    printf("unable to open file %s", file_name);
  }

  while (fscanf(file, "%d", &i) == 1)
  {
    n++;
    printf("%d\n ", i);
    *result += i;
    printf("\n we are at row nr. %d sum of this number and all numbers before is: %d\n", n, *result);
  }
  fclose(file);
  return n;
}
int *scanFreq(const char *file_name, int *A, int *B, int *resultTab)
{
  FILE *file = fopen("numbers.txt", "r");
  int i = 0;
  int n = 0; //row number//

  if (file == NULL)
  {
    printf("unable to open file %s", file_name);
  }

  while (fscanf(file, "%d", &i) == 1)
  {
    n++;
    *resultTab += i;
    B[n] = i;
    A[n] = *resultTab;
  }
  fclose(file);
  return 0;
}

int freqRepeat(int *A, int *B, int freqCount)
{
  int lastFrequency;

  lastFrequency = freqCount;
   freqCount = freqCount + freqCount;
  A = increaseSize(A, freqCount);

  printf("\n\nwcis enter\n\n");
  getchar();

  for (int i = 1; i < 15; i++)
  {
    printf("array argument after increasing array size %d \n", A[i]);

    // why some of the arguments have been changed ????????
    }
return 0;
}
int *increaseSize(int *A, int freqCount)
{

  return realloc(A, 2 * sizeof(int));
}


text input:
-14
+15
+9
+19
+18
+14
+14
-18
+15
+4
-18
-20
-2
+17
+16
-7
-3
+5
+1
-5
-11
-1
-6
-20
+1
+1
+4
+18
+5
-20
-10
+18
+5
-4
-5
-18
+9
+6
+1
-19
+13
+10
-22
-11
-14
-17
-10
-1
-13
+6
-17

标签: carraysmallocrealloc

解决方案


您无条件地调整数组的大小以仅包含两个 int元素。总是。对这两者之外的元素的任何访问都将导致未定义的行为

你可能打算做

return realloc(A, freqCount * sizeof(int));

推荐阅读