Allocation of memory for char array

前端 未结 10 850
孤独总比滥情好
孤独总比滥情好 2021-01-02 12:45

Let\'s say you have-

struct Person {
    char *name;
    int age;
    int height;
    int weight; 
 };

If you do-

struct Pe         


        
10条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-02 13:35

    Don't assume that the memory storing the pointer for name is the same as the memory storing the data for name. Assuming a 4 byte word size, you have the following:

    • char * (4 bytes)
    • int (4 bytes)
    • int (4 bytes)
    • int (4 bytes)
    • ================
    • total: 16 bytes

    which is: sizeof(char*) + sizeof(int) + sizeof(int) + sizeof(int). C knows the size because you've told it the size of the elements in the struct definition.

    I think what you are confused about is the following:

    The contents at the char * will be a memory location (e.g. 0x00ffbe532) which is where the actual string will be stored. Don't assume that the struct contents are contiguous (because of the pointer). In fact, you can be pretty sure that they won't be.

    So, to reiterate, for an example struct Person (this is just an example, the locations won't be the same in a real program.)

    • location : [contents]
    • 0x0000 : [0x00ffbe532]
    • 0x0004 : [10]
    • 0x0008 : [3]
    • 0x000C : [25]

    • 0x00ffbe532 : [I am a string\0]

提交回复
热议问题