Is there a standard pointer size declaration?

前端 未结 4 1357
无人及你
无人及你 2021-01-20 17:03

I have struct with padding in char (oops, my bad). I would like to subtract a pointer size. Do you know a standard pointer size declaration, or a standard macro

相关标签:
4条回答
  • 2021-01-20 17:51

    Do you want the C-standard answer, or the answer that works pretty much all the time?

    Usually, all pointers to data are the same size, which is sizeof(void*).

    But since you tagged "C" and "standards", note that this is not required by the C standard. I think it is required by POSIX, and is also true on Win32, and none of the common modern architectures have instructions involving different-sized pointers. One scenario where you have different-sized pointers is segmented memory architectures with "near" and "far" pointers, although of course only one of those can be a "plain" pointer in C on any given implementation. Another scenario, is that in theory a pointer to int could be 2 bits smaller than a pointer to char, if an int is always 4-aligned. If the memory space was, say, 64MB, that could mean that an int* fits in 2 bytes, whereas a char* or void* requires 3. So the C standard allows different sizes for different types, in this case sizeof(int*) < sizeof(char*).

    So, both for clarity, and a guarantee of correctness, if p is a pointer then its size is sizeof p.

    As Steve Townsend says in his comment, it seems likely that if you ask another question about your code, you may be able to fix your real problem. Knowing the size of a pointer does not directly tell you much about the layout of a struct containing a pointer.

    0 讨论(0)
  • 2021-01-20 17:58

    If you are looking for a portable way to find the offset in bytes of a structure member then you want to use the offsetof() macro defined in stddef.h:

    #include <stdio.h>
    #include <stddef.h>
    
    int main(void)
    {
        struct s {
            int i;
            char c;
            double d;
            char a[];
        };
    
        /* Output is compiler dependent */
    
        printf("offsets: i=%ld; c=%ld; d=%ld a=%ld\n",
                (long) offsetof(struct s, i),
                (long) offsetof(struct s, c),
                (long) offsetof(struct s, d),
                (long) offsetof(struct s, a));
        printf("sizeof(struct s)=%ld\n", (long) sizeof(struct s));
    
        return 0;
    }
    

    Output

    $ ./a.out
    offsets: i=0; c=4; d=8 a=16
    sizeof(struct s)=16
    
    0 讨论(0)
  • 2021-01-20 18:05

    You can use sizeof(void*) directly.

    0 讨论(0)
  • 2021-01-20 18:07

    sizeof (void *)

    0 讨论(0)
提交回复
热议问题