My problem is that my integer array’s values change when it is passed to the function calculate. The values are correct for indexes 0, and 2->5.
For some reason, indexes 1 and 6+ are not the correct values.
Below is my code.
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int* generate_rand (int length, int MAX_ARRAY);
void calculate (int *array_ptr, int length, int *mean, int *sd);
main() {
srand(time(NULL));
int a;
printf("\nArray length?: ");
scanf("%d", &a);
int* array_ptr2;
array_ptr2 = generate_rand(a, 100);
//int mean, sd;
int* *mean;
int* *sd;
int i = 0;
for (i = 0; i < 10; i++) {
printf("Array2: %d\n", *(array_ptr2 + i));
}
calculate(array_ptr2, a, *mean, *sd);
//printf("Mean: %d\n", (int)*mean);
}
int* generate_rand (int length, int MAX_ARRAY) {
int arr[length];
int i;
for (i = 0; i < 10; i++) {
int r = rand()%MAX_ARRAY;
arr[i] = r;
printf("Rand: %d\n", arr[i]);
}
int *arrPtr;
arrPtr = &arr[0];
return arrPtr;
}
void calculate (int *array_ptr, int length, int *mean, int *sd) {
int sum;
int i;
for (i = 0; i < length; i++) {
printf("Array: %d\n", *(array_ptr + i));
sum += *(array_ptr + i);
//array_ptr++;
printf("Sum: %d, i:%d\n", sum, i);
}
//*mean = sum / length;
}
Do you know what I’m doing wrong?
The problem is that you are returning the address of a local variable of a function. Local variables of functions cease to exist after a function has exited, so the returned pointer suddenly becomes dangling (as in, not pointing to anything useful).
You need to allocate memory for your array with
malloc, because the memory returned frommallocwill exist until it is freed withfree(which you can call anytime afterwards).When you no longer need the array returned from this function, pass it to
freeto release the memory, e.g.: