Allocation of memory for char array

前端 未结 10 710
孤独总比滥情好
孤独总比滥情好 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]

    0 讨论(0)
  • 2021-01-02 13:40

    I think you should also need to allocate memory for the name attribute

    0 讨论(0)
  • 2021-01-02 13:42

    The name member is just a pointer. The size of a pointer varies with the underlying architecture, but is usually 4 or 8 bytes nowadays.

    The data that name can point to (if assigned later) should be laid out in an area that does not coincide with the struct at all.

    At the language level, the struct doesn't know anything about the memory that the name member is pointing to; you have to manage that manually.

    0 讨论(0)
  • 2021-01-02 13:42

    It doesn't. You have to do that too.

    struct Person *who = malloc(sizeof(struct Person));
    who->name = malloc(sizeof(char) * 16); /* for a 15+1 character array */
    
    0 讨论(0)
提交回复
热议问题