Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Return a struct pointer containing a 2d array as a function parameter

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading