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

Getting the address of an array element and saving it

I am trying to get the address of a particular element in an array. I know I can get the root address, but how do I get the element address:

struct s_name
{
    char *name;
    int age;
};

I don’t know the number of names until runtime, so

s_name *allNames;
maxNames = 10; // this is from somewhere else
allNames = malloc(sizeof(s_name) * maxNames);

So to get the second element, normally, allNames[1]

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

But I want to reverse this array in another array

s_name *revNames;
revNames = malloc(sizeof(s_name) * maxNames);

int revIndex = 0;

for ( int i = maxNames - 1; i >= 0; i-- , revIndex++ )
    revName[revIndex] = allNames[i];

So revName[0] should point to allNames[maxNames - 1] and I should be able to print revName[0].name

This fails.

I have tried

revName[revIndex] = &allNames[i];

I do not understand some fundamental thing here. With pointer arithmetic, allNames[1] should be the root memory address of allNames plus the size of s_name, to get at the actual address of the element, which I should be able to save and access.

There has to be some way to do this…

>Solution :

You seem to want for revNames to be a pointer to an array of pointers.

s_name **revNames = malloc(sizeof(*revNames) * maxNames);
for (int i = maxNames - 1; i >= 0; i--, revIndex++) {
    revName[revIndex] = &allNames[i];
}

Tip: sizeof(*revNames) is equal to sizeof(s_name*).

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