-2

I have the following:

typedef struct
{
    string city;
    int temp;
}
avg_temp;

avg_temp temps[NUM_CITIES];

void sort_cities(void);

int main(void)
{
    temps[0].city = "Austin";
    temps[0].temp = 97;

    temps[1].city = "Boston";
    temps[1].temp = 82;

    temps[2].city = "Chicago";
    temps[2].temp = 85;

    temps[3].city = "Denver";
    temps[3].temp = 90;

    temps[4].city = "Las Vegas";
    temps[4].temp = 105;

    temps[5].city = "Los Angeles";
    temps[5].temp = 82;

    temps[6].city = "Miami";
    temps[6].temp = 97;

    temps[7].city = "New York";
    temps[7].temp = 85;

    temps[8].city = "Phoenix";
    temps[8].temp = 107;

    temps[9].city = "San Francisco";
    temps[9].temp = 66;
}

Now, the sizeof(temps) = 160, sizeof(temps[0]) = 16, sizeof(temps[0].city) = 8 and sizeof(temps[0].temp = 4.

since city and temp take up 12 what takes up 4 in temps[0] ?

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
DCR
  • 14,737
  • 12
  • 52
  • 115
  • 2
    Whatever is `string` here in C? You should also check `alignof(avg_temp)`. – tadman May 15 '23 at 22:05
  • 2
    If `string` is actually `char*` then you're getting penalized by alignment requirements as this struct *must* live on an 8-byte boundary, at least on 64-bit systems with 8-byte sized pointers. – tadman May 15 '23 at 22:07
  • 2
    For those wondering, [cs50](https://github.com/cs50/libcs50) is a library designed to make life easier for beginners in C and creates a named typedef `string` which is really a `char *`. I personally disagree with that teaching philosophy, but many low level intro to programming courses use it and thus we already see many questions on SO using it, so, expect to see more — it isn’t going away. – Dúthomhas May 15 '23 at 22:16
  • 2
    Your question should include [mre]. In particular, you should show us your entire source file, including any and all `#include` directives. There is no `string` type in standard C; you're probably using `cs50`, and if so, you should add the [tag:cs50] tag. – Keith Thompson May 15 '23 at 22:36

1 Answers1

5

This structure

typedef struct
{
    string city;
    int temp;
}
avg_temp;

is aligned according to the more strict alignment of its data member of the type string (which is evidently an alias for the type char *) that has the size equal to 8.

So the structure is appended with 4 bytes.

pmacfarlane
  • 3,057
  • 1
  • 7
  • 24
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335