Dark Templar
Dark Templar

Reputation: 1137

One last thing about C pointers: confused about what this snippet of code will do?

I have a pointer value stored at b+4 that I would like to load 'a' into. So essentially I have that b+4 is a pointer to a pointer to an unsigned int (the address pointed to by a). However, I was wondering whether this code would actually store the entirety of 'a' (since 'a' is 4 bytes), or if the left-hand value would just store 1 byte:

    void *a = //something;
    *((unsigned **)((char*)b+4)) = a;

I am confused as to whether the second line will store 'a' as a char, or as an unsigned int...

*edit: So then, would it be any different if I did:

    *((char *)b + 4) = a;

Upvotes: -1

Views: 116

Answers (2)

Alok Save
Alok Save

Reputation: 206508

*((unsigned **)((char*)b+4)) = a;

Resolves to a pointer.
A pointer is a type which just points(stores) the address of the type(which it is declared of). Also, note that all pointers on an system will have essentially the same size.

So in this case,
The pointer at b+4 just points/stores the address which a stores.
You will have two pointers pointing to the same address.

    |----------|                                 
    |   b+4    |                            
    |          |  1000                       
    |   2000   |                             
    |----------|                               
          |                                           
          |
          |
          |
          -------------------->|----------|
                               |   num    |
          -------------------->|          |  2000
          |                    |    2     |  This is what a points to   
          |                    |----------|
          |
          |
    |----------|                             
    |     a    |                            
    |          |  3000                       
    |   2000   |                             
    |----------|    

*((char *)b + 4) = a;

Does not resolve to a pointer type, You are trying to assign a pointer to non pointer type, So it should give a warning.

Upvotes: 1

Ken Russell
Ken Russell

Reputation: 2378

All pointers have the same size. So it doesn't matter if RHS points to a 4 byte variable and LHS points to a 1 byte variable. What matters is, you cast the RHS before assigning to LHS. Therefore the following is valid.

int c;
void * a = &c;

unsigned d;
unsigned * e = &d;
unsigned ** b = &e;
b = (unsigned **)&a;

Upvotes: 1

Related Questions