Deepu Deepu - 1 year ago 43
C Question

Finding the address of nested structure member variables

Dear stackoverflow Enthusiasts,

First of all I am a novice in stackoverflow, so I apologise in advance for any mistakes I commit.

This is kind of a C puzzle. or atleast I was puzzled by it. The code is given below.

struct outer_str
{
struct nest_str1
{
int mem1;
};
struct nest_str2
{
int mem2;
}nest_var2;
}outer_var;

int main()
{
outer_var.nest_var2.mem2 = 111;
printf("\n\nThe value of mem2 is %d\n\n",outer_var.nest_var2.mem2);

// Statement to assign mem1 of nest_str1 with a value say 333;
// Statement to print the value of mem1 of nest_str1;

return 0;
}


As the comments suggest you have to access the member variable mem1 of the nested structure nest_str1. Also please note that there are no structure variables declared for the nested structure nest_str1.

Hoping against hope I tried the following code, imitating a bit of C++.

outer_var.nest_str1.mem1=333;


When I compiled the program using GCC 4.6.3, The following error was shown

"struct outer_str has no member named 'nest_str1' ".


Then I thought about finding the address of nest_str1 from the address of nest_var2 which is the structure variable of nested structure nest_str2. I tried the following code,

int main()
{
int offset;
struct nest_str1 * addr;
offset=sizeof(int); // There is only one integer mem1 in nest_str1
addr=(struct nest_str1 *)((int *) & (outer_var.nest_var2) - offset);
addr->mem1=333;
printf("\n\nThe value of mem1 is %d\n\n",addr->mem1);
return 0;
}


The program compiled O.K. But the output was not what I expected. I got a run time error.

Segmentation fault (core dumped)


Now I don't even know whether my approach was correct or not. So I am hoping for some suggestions. I am also worried that I might have overlooked some obviously simple solution.

I would also like to know whether we can access mem1 in the code given below.

struct outer_str
{

struct nest_str1
{
int mem1;
};

}outer_var;


I thank every one in advance for your time and patience.

Nim Nim
Answer Source

There is no member of outer_var that will allow you to access mem1 (you've not declared one, you just defined a type called nest_str1.)

Change this to:

struct outer_str
{

  struct nest_str1
  {
     int mem1;
  } nest_var1;  // now there is a member!

}outer_var;

Now you can:

outer_var.nest_var1.mem1 = 100;

Your attempt is just plain wrong, there is no storage for mem1, so even if your code worked, you would most likely end up writing to the location of mem2.