我正在从文件中读取整数,当我尝试增加我的数组时,我在第二次调用时遇到了分段错误growMyArray(struct myArray)
,特别是在int *grownArray = malloc(arrayToGrow.maxCount * sizeof(int));
:
struct myArray growMyArray(struct myArray arrayToGrow) {
arrayToGrow.maxCount *= 2;
int *grownArray = malloc(arrayToGrow.maxCount * sizeof(int));
int i;
for (i = 0; i < arrayToGrow.count; i++)
grownArray[i] = arrayToGrow.numbers[i];
free(arrayToGrow.numbers);
arrayToGrow.numbers = grownArray;
return arrayToGrow;
}
我的结构:
typedef struct myArray {
int count;
int maxCount;
int *numbers;
} myArray;
从输入重定向读取:
struct myArray getRandomNumbers() {
struct myArray randomNumbers;
randomNumbers.count = 0;
randomNumbers.maxCount = DEFAULT_SIZE;
randomNumbers.numbers = malloc(randomNumbers.maxCount * sizeof(int));
while (scanf("%d", &randomNumbers.numbers[randomNumbers.count]) == 1) {
randomNumbers.count++;
if (randomNumbers.count > randomNumbers.maxCount)
randomNumbers = growMyArray(randomNumbers);
}
return randomNumbers;
}
我觉得这特别奇怪,因为增长数组第一次总是有效,但第二次永远不会有效。我DEFAULT_SIZE
在一组大小为 200000 的测试数据上使用了多个值,范围从 2 到 20000。
是否有明显的原因为什么我在第二次调用时遇到分段错误growMyArray
,特别是在int *grownArray = malloc(arrayToGrow.maxCount * sizeof(int));
?