Here I have a user-defined structure "person" that stores two pointers one for the name and one for the phone number. I create an array people of length 2 of type person.
Each of the elements in people take 16 bytes (8 for each pointer)
When print the addresses of people[0] and people[1] I see that they are correctly 16 bytes apart.
Also, the fields name & number are 8 bytes apart for a given element in the array.
However, wouldn't people[0].name occupy more than 8 bytes of memory since each character (char type) takes 1 byte and people[0].name has 15 characters??? Thanks

  #include <stdio.h>
  #include <stdlib.h>

  typedef char* string;
  typedef struct
      string name;
      string number;

  int main(void)
      person people[2];
      people[0].name = "Brian";
      people[0].number= "+1-222-999-1000";
      printf("Size of Person: %lu\n",sizeof(person));
      printf("Size of People[0]: %lu\n",sizeof(people[0]));
      printf("Address of People[0]: %p\n",&people[0]);
      printf("Address of People[0].name: %p\n",&people[0].name);
      printf("Address of People[0].number: %p\n",&people[0].number);
      printf("Address of People[1]: %p\n",&people[1]);

This is what I get when running the program:

Size of Person: 16
Size of People[0]: 16
Address of People[0]: 0x7fff8bd21990
Address of People[0].name: 0x7fff8bd21990
Address of People[0].number: 0x7fff8bd21998
Address of People[1]: 0x7fff8bd219a0

Both name and number are declared as char * (ie, a pointer variable). Pointers hold addresses and the sizeof(char*) is 8 bytes in a 64-bit system like the CS50 IDE. So people will have a size of 16 bytes, as you're seeing in your print statements.

What name and number actually point to is irrelevant to the size of the pointer itself. The memory for the actual string "+1-222-999-1000" in your example is allocated when the program is compiled. You've used a string literal which is hard-coded into the actual assembler code.

  • Great, thanks! Makes sense now! Jun 6 at 14:23

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .