Get size of pointer in C

后端 未结 3 560
鱼传尺愫
鱼传尺愫 2020-12-08 15:40

How do I get the size of a pointer in C using sizeof? I want to malloc some memory to store a pointer (not the value being pointed to).

相关标签:
3条回答
  • 2020-12-08 15:57

    This should do the trick:

    sizeof(void*)
    
    0 讨论(0)
  • 2020-12-08 16:04
    char *ptr;
    char **ptr2 = malloc(sizeof(ptr));
    

    should be able to achieve your purpose. No matter what the platform is, this code should work.

    0 讨论(0)
  • 2020-12-08 16:07

    Given an arbitrary type (I've chosen char here, but that is for sake of concrete example):

    char *p;
    

    You can use either of these expressions:

    sizeof(p)
    sizeof(char *)
    

    Leading to a malloc() call such as:

    char **ppc = malloc(sizeof(char *));
    char **ppc = malloc(sizeof(p));
    char **ppc = malloc(sizeof(*ppc));
    

    The last version has some benefits in that if the type of ppc changes, the expression still allocates the correct space.

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