gpt4 book ai didi

c - 增加数组大小。在 increaseSize 函数之后,同一数组的某些参数无效。铿锵

转载 作者:太空宇宙 更新时间:2023-11-04 02:23:32 24 4
gpt4 key购买 nike

该程序从“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

最佳答案

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

你可能是想做

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

关于c - 增加数组大小。在 increaseSize 函数之后,同一数组的某些参数无效。铿锵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54322483/

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