Pointer arithmetic for structs

后端 未结 5 2147
鱼传尺愫
鱼传尺愫 2021-02-07 08:02

Given a struct definition that contains one double and three int variables (4 variables in all), if p is a pointer to this struct with a value 0x1000, what value does p++ have?<

相关标签:
5条回答
  • 2021-02-07 08:48
    p = p + sizeof(YourStruct)
    

    The compiler is free to decide what sizeof will return if you don't turn padding off.

    0 讨论(0)
  • 2021-02-07 08:49

    The answer is that it is at least

    sizeof(double) + (3*sizeof(int))
    

    Thew reason it's "at least" is that the compiler is more or less free to add padding as needed by the underlying architecture to make it suit alignment constraints.

    Let's say, for example, that you have a machine with a 64-bit word, like an old CDC machine. (Hell, some of them had 60-bit words, so it would get weirder yet.) Further assume that on that machine, sizeof(double) is 64 bits, while sizeof(int) is 16 bits. The compiler might then lay out your struct as

    | double     | int | int | int | 16 bits padding |
    

    so that the whole struct could be passed through the machine in 2 memory references, with no shifting or messing about needed. In that case, sizeof(yourstruct_s) would be 16, where sizeof(double)+ (3*sizeof(int)) is only 48 14.

    Update

    Observe this could be true on a 32-bit machine as well: then you might need padding to fit it into three words. I don't know of a modern machine that doesn't address down to the byte, so it may be hard to find an example now, but a bunch of older architectures ould need this.

    0 讨论(0)
  • 2021-02-07 08:51

    A Increment in base address of a data type is equal to base address + sizeof(data type)

    0 讨论(0)
  • 2021-02-07 08:53

    Pointer arithmetic is done in units of the size of the pointer type.

    So if you do p++ on a pointer to your struct, p will advance by sizeof *p bytes. i.e. just ask your compiler for how big your struct is with the sizeof operator.

    0 讨论(0)
  • 2021-02-07 08:56
    struct foobar *p;
    p = 0x1000; 
    p++;
    

    is the same as

    struct foobar *p;
    p = 0x1000 + sizeof(struct foobar);
    
    0 讨论(0)
提交回复
热议问题