I created a function that fills the values of a struct with ints and is supposed to return a pointer to that same struct. However, when I print what the pointer references, it prints garbage values.
Here is my code:
#include <stdlib.h>
#include <stdio.h>
struct Map * collect_values(int n, int *arr);
struct Map{
int value, position;
};
int main(){
int size, i;
scanf("%d", &size);
int *arr = (int*) malloc(size*sizeof(int));
struct Map *p = collect_values(size,arr);
for(i = 0; i < size; i++){
printf("%d : %d\n", p[i].value, p[i].position);
}
return 0;
}
struct Map * collect_values(int n, int *arr){
int i, position = 0;
struct Map array[n];
for(i = 0; i < n; i++){
scanf("%d",&arr[i]);
array[i].value = arr[i];
array[i].position = position;
position++;
}
struct Map *ptr = &array[n];
return ptr;
}
I'm pipelining values from a file, so the scanf() works fine, and I've printed from the collect values() so I know that it is creating the struct properly.
However, when I print from the main method, the output is:
-485221568 : 32766
-1529319768 : 32767
24 : 48
-485221520 : 32766
-485221776 : 32766
32766 : 0
872480919 : -968757580
0 : 0
0 : 0
0 : 0
I've tried using p[i]->value
, but it doesn't compile. What am I doing wrong?