I am struggling really hard to understand this behavior so maybe someone can shed some light on the situation.
I simply can’t figure out why I can’t return a pointer to a struct from a method and expect to be able to still re-use it afterwards.
As you can see the generateSmallMatrix() method creates an int[] array and sets it inside the ysmf struct that I then return to main. Main then takes the ysmf* and calls printArray (again). And on the third try the array cannot be retrieved any more..
It’s driving me crazy..
I have checked with my Eclipse debugger that on all calls the location of matrix->A is identical (0x7fffffffe180 – so for all I know about C pointers any form of accessing that int should return the correct value – be it *(ax++) or ax[i]) .. but neither do..
Very frustrating to say the least, so here is the code:
#include <stdio.h>
#include <stdlib.h>
typedef struct sparseMatrix
{
int* A;
} ysmf;
void printArray(int* ax, int length) {
int i = 0;
for (i = 0; i < length; i++) {
printf("%i,", ax[i]);
}
printf("\n");
}
ysmf* generateSmallMatrix()
{
ysmf *matrix = malloc(sizeof(ysmf));
int a[] = {1,2,3,9,1,4};
printArray(a, 6); // returns 1,2,3,9,1,4,
matrix->A = a;
printArray(matrix->A, 6); //returns 1,2,3,9,1,4,
//printArray(matrix->A, 6);
return matrix;
}
int main(void) {
ysmf* matrix = generateSmallMatrix();
printArray(matrix->A, 6); //returns 1,6,-7856,32767,1,4,
return EXIT_SUCCESS;
}
You can see the problem occuring where I have inserted the comments.
I know this is probably something totally basic I shouldn’t have missed..
Because
ais a local array, whose lifetime ends when thegenerateSmallMatrix()function ends. Accessing it after that results in undefined behaviour.