增加数组大小。在increaseSize函数之后,同一数组的某些参数无效。 ç郎

时间:2019-01-23 08:01:42

标签: c arrays malloc realloc

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

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

在调用了提及的函数increaseSize之后,出现了一个问题,因为只有一部分参数保持不变,并且很少有参数变成很大的数目。这是一个主要问题。谁能帮我一些忙吗?谢谢

ps。我将在代码末尾输入示例文本文件。

#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

1 个答案:

答案 0 :(得分:2)

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

您可能打算这样做

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