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

typedef with array in c

Something wrong with my understanding of typedef for arrays in C.
Code just not worked as expected. I provide some screenshot while debugging this simply code. And you can see there, that only firs element of array[0] was assigned right to 0xff. [1] and [2] elements was not assigned.

Exploring assembly code of change_array function, I noticed, that address of array + 0x28 and array + 0x50 was used for assigning [1] and [2] elements. It looks like TMyArray[10][n] was used.

So, I have no idea how to access array elements in function change_array.

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

    typedef int TMyArray[10];
    TMyArray test_array = {0};

    void change_array(TMyArray * array)
    {
    *array[0] = 0xff;
    *array[1] = 0xff;   // wrong!
    *array[2] = 0xff;   // wring!
    }

    int main()
    {
    change_array(&test_array);
    return 0;
    }


debugger screenshot

I would appreciate any explanation of this behavior.

>Solution :

The unary * has lower precedence than the postfix [] operator, so the expression

*array[1]

is parsed as

*(array[1])

meaning you’re trying to dereference the individual array element, which isn’t what you want. Instead, you need to dereference array first and then index into the result:

(*array)[0] = 0xff;
(*array)[1] = 0xff;
(*array)[2] = 0xff;
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