I was doing my exercise of C Language. In the exercise I was encountered by a question in which author says you to perdict the correct answer; I was uable to perdict it, so I compiled it to get the answer, the source code is this:

#include <stdio.h>
int main ()
  struct {
    int x, y;
  }s[] = {10, 20, 15, 25, 8, 75, 6, 2};

  int *i;

  i = s;
  printf("%d", s[i[7]].x);
  return 0;


It yields this output:


I'm unable to understand why the answer is 8 whereas in my thinking it should be 15.
Please help me.....!!!!!

Recommended Answers

All 2 Replies

I hope that the question highlighted that this isn't an example of good code.

You've created a structure that holds 2 integers (side by side in memory). You then created an array of 8 integers (all side by side in memory). You then said that this array is an array of structures (thus, every 2 integers counts as one unit).

Then you introduced a pointer (int *) i that points to the same memory. The thing that's important here is the datatype. The compiler thinks i is pointing to an array of integers, and the compiler thinks that s is pointing to an array of structures, thus it indexes them differently.

You should be able to figure it out with that information.

Member Avatar

At first glance I also came up with either 75 or 15, but remember that arrays are 0-based. So bearing in mind what Hiroshe has mentioned; find i[7] and say the result is = a, then find s[a].x

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.