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]
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*).