In the following code, why does directly setting a pointer to a struct address work, but returning it from a function the exact same way not work?
#include <stdio.h>
#include <stdint.h>
typedef struct
{
uint8_t data[5][1];
} TST_T;
TST_T s_Data;
void GetData(TST_T *pData)
{
pData = &s_Data;
}
int main()
{
s_Data.data[0][0] = 1;
s_Data.data[1][0] = 2;
s_Data.data[2][0] = 3;
s_Data.data[3][0] = 4;
s_Data.data[4][0] = 5;
//TST_T *pData = &s_Data; //<< This works
TST_T *pData;
GetData(pData); //<< This doesn't
for(uint8_t i=0; i<5; i++)
{
printf( "%d\n", pData->data[i][0] );
}
return 0;
}
Solution: (Thanks XbzOverflow!)
#include <stdio.h>
#include <stdint.h>
typedef struct
{
uint8_t data[5][1];
} TST_T;
static TST_T s_Data;
void GetData(TST_T **pData)
{
(*pData) = &s_Data;
}
int main()
{
s_Data.data[0][0] = 1;
s_Data.data[1][0] = 2;
s_Data.data[2][0] = 3;
s_Data.data[3][0] = 4;
s_Data.data[4][0] = 5;
//TST_T *pData = &s_Data; //<< This works
TST_T *pData;
GetData(&pData); //<< This NOW works!
for(uint8_t i=0; i<5; i++)
{
printf( "%d\n", pData->data[i][0] );
}
return 0;
}
disregard this.. stack overflow making me write more text bc there is too much code vs. text describing the code
You did not change the pData pointer in main function at all.
You copy the pointer, and set the value of the copy.
If you want to change the value of the pointer, try:
void foo(TST_T** pt_to_pt)
{
(*pt_to_pt) = &something;
}
foo(&pData);
This will change the value of the pointer in main function.