-3

This is one of the questions asked in one of the interview. I dont know its good to post it or not. But the answer would help me.

We know that local variables will be stored in stack, suppose we had a code something like this.

int main()
{
    struct ST1 {
        char ch1;
        short s;
        char ch2;
        long long ll;
        int i;
    }s1;
    function(s1);// pasing structure to function
// some code
}

function(struct ST1 s1) {
    // code to show the order in which the fields of the structure are stored on the run time stack
}

How can it be possible to write a code in function to show the order in which the fields of the structure are stored in run time stack?

Megharaj
  • 1,589
  • 2
  • 20
  • 32
  • The &variablename operation returns the address of the variable. If you know the addresses of all of the variables in a struct you can determine how they are arranged in memory. You can also use the offsetof macro to do the same thing. [offsetof](http://en.wikipedia.org/wiki/Offsetof) โ€“ jim mcnamara Oct 04 '13 at 12:04

2 Answers2

3

How can it be possible to write a code in function to show the order in which the fields of the structure are stored?

We don't need to; the C language standard guarantees the order:

[C99 ยง6.7.2.1] Within a structure object, the non-bit-field members and the units in which bit-fields reside have addresses that increase in the order in which they are declared.

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
  • I took it to mean were the struct members contiguous, packing/no packing. Otherwise, as you state, there is no point to doing this in code. +1 โ€“ jim mcnamara Oct 04 '13 at 12:06
  • 1
    @oli but this http://stackoverflow.com/a/2749096/1292348 says the structure will be stored in the order which we declare them. I even verified that. โ€“ Megharaj Oct 04 '13 at 12:13
1

I agree with above points, about the un-necessity of doing such thing.

In any case, if you really want to do something like this...

//changed to typedef, for convenience

typedef struct {
    char ch1;
    short s;
    char ch2;
    long long ll;
    int i;
}ST1;

void function(ST1 parameter);

//Function implementation:

void function(ST1 parameter)
{
    printf("\nch1 address: %ld", &(parameter.ch1));
    printf("\ns address: %ld", &(parameter.s));
    printf("\nch2 address: %ld", &(parameter.ch2));
    printf("\nll address: %ld", &(parameter.ll));
    printf("\ni address: %ld", &(parameter.i));
}

Or you can use a way to evaluate addresses of struct

The only utility I can see, is in case you have a union, and you want to be sure about endianness (this can apply to microcontrollers of different architecture).