0

I know this is a very basic question in C, so I apologize beforehand if this is naive: I'm just learning the basics a few days in.

int main() {

    // initialize the variables
    int num_whitespaces, num_other;
    int num_digits[10];
    printf("%lu", sizeof(num_digits));

}

This prints 40, which seems odd to me. Why wouldn't this print 10, which would be the length of the array in javascript or so.

  • I have no knowledge about `C` but I know that size of `int` is 32 bits (4 bytes). – Vlad DX Aug 22 '19 at 23:01
  • 1
    Did you try already searching for similar questions? Probably it's because it returns a size of array (all it's elements), not just length - amount of elements. So it seems like int is 4 bytes in this case – misticos Aug 22 '19 at 23:01
  • Welcome to SO! Please search the existing questions before posting. It's unlikely you'll be encountering any problems that someone hasn't already solved many times over. See [ask]. – ggorlen Aug 22 '19 at 23:04
  • @VladimirSerykh that's completely wrong. `int` in C must be at least 16 bits, otherwise the standard doesn't mandate a fixed size because C is supposed to be portable. So for example `int` will be 18-bit on an 18-bit architecture – phuclv Aug 23 '19 at 00:27
  • @Shared you're also invoking undefined behavior because you used the wrong format specifier. [To print a `size_t` (which is the result of `sizeof`) use `%zu`](https://stackoverflow.com/q/940087/995714) – phuclv Aug 23 '19 at 00:28

2 Answers2

3

sizeof returns the size in memory. Not the length of something.

Same for C++ and this link has the same example :) https://en.cppreference.com/w/cpp/language/sizeof

size of empty class:              1
size of pointer:                  8
size of array of 10 int:         40
size of array of 10 int (2):     40
length of array of 10 int:       10
length of array of 10 int (2):   10
size of the Derived:              8
size of the Derived through Base: 4

Getting the length is pretty difficult in C: array_length in C

Julian
  • 33,915
  • 22
  • 119
  • 174
0

sizeof returns the size of an object in bytes

An int is 4 bytes. sizeof(int[10]) is 40.

Aziz
  • 20,065
  • 8
  • 63
  • 69