[英]Run-Time Check Failure #2 - Stack around the variable 'array' was corrupted
I have this code here which is working but when it gets to the very end it throws a run time check and I'm not sure why, also trying to free the memory at the end will result in a different exception "Access violation reading location 0x00000024" and I can't figure out what the problem is我这里有这段代码正在工作,但是当它运行到最后时,它会引发运行时检查,我不知道为什么,还试图在最后释放 memory 将导致不同的异常“访问冲突读取位置0x00000024”,我不知道是什么问题
# include<stdio.h>
# include <stdlib.h>
int createTheArray(int *array) {
int y;
printf("Enter the number of random numbers you wish to create and store: ");
scanf_s("%i", &y);
array = (int *)calloc(y,sizeof(int));
if (array == NULL)
printf("Out of memory");
else {
printf("Memory allocated \n");
return y;
}
}
void populateArray(int* array, int y) {
int x;
for (x = 0; x < y; x++) {
array[x] = rand() % 100;
}
for (x = 0; x < y; x++) {
printf("array[%i]: %i\n", x ,array[x]);
}
}
void operateArray(int* array, int y) {
int i,sum=0,high=0,low=array[0];
float average;
for (i = 0; i < y; i++) {
sum = sum + array[i];
if (array[i] > high)
high = array[i];
if (array[i] < low)
low = array[i];
}
average = (float) sum / y;
printf("\n");
printf("Sum: %i \n", sum);
printf("high: %i \n", high);
printf("low: %i \n", low);
printf("Average: %.1f \n", average);
}
main() {
int* array = (int *)calloc(1,sizeof(int));
int y;
y = createTheArray(array);
populateArray(array,y);
operateArray(array, y);
free(array);
return 0;
}
Here is the design I'm talking about.这是我正在谈论的设计。 This avoids needing to have a function return two things.
这避免了需要让 function 返回两件事。 In general, a function should have one purpose ("create the array") and not have the additional hidden function ("ask the user for the size").
一般来说,一个 function 应该有一个目的(“创建数组”),并且没有额外的隐藏 function (“向用户询问大小”)。 Here's what I mean:
这就是我的意思:
#include <stdio.h>
#include <stdlib.h>
int * createTheArray(int size) {
int *x = (int*)calloc(size, sizeof(int));
if (x == NULL)
printf("Out of memory");
else
printf("Memory allocated \n");
return x;
}
void populateArray(int *array, int y) {
int x,k;
for (x = 0; x < y; x++) {
array[x] = rand() % 100;
}
for (k = 0; k < y; k++) {
printf("array[%i]: %i\n", k, array[k]);
}
}
void operateArray(int* array, int y) {
int i,sum=0,high=0,low=array[0];
float average;
for (i = 0; i < y; i++) {
sum = sum + array[i];
if (array[i] > high)
high = array[i];
if (array[i] < low)
low = array[i];
}
average = (float) sum / y;
printf("Sum: %i \n", sum);
printf("high: %i \n", high);
printf("low: %i \n", low);
printf("Average: %.1f \n", average);
}
main() {
int *array;
int y;
printf("Enter the number of random numbers you wish to create and store: ");
scanf("%i", &y);
array = createTheArray(y);
populateArray(array,y);
operateArray(array, y);
free(array);
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.