0

currently I'm doing book called "C Primer Plus" by Stephen Prata. I'm on chapter 10 it is about pointers and arrays.

Code looks like this

#include <stdio.h>
#define SIZE 10
long sum (int tab[], int n);
int main (void)
{
    int balls[SIZE] = {20, 10, 5, 39, 4, 16, 19, 26, 31, 20};
    long wynik;
    wynik = sum(balls, SIZE);
    printf("Number of balls is %ld, sizeof int = %ld\n", wynik, sizeof(int));
    printf("Size of balls array is %zd bytes.\n", sizeof balls);

    return 0;
}
long sum(int tab[], int n)
{
    int i;
    int suma = 0;
    for (i = 0; i < n; i++)
        suma += tab[i];
    printf("Size of tab array is %d bytes\n", sizeof tab);
    return suma;
}

Output:

Size of tab array is 8 bytes
Number of balls is 190, sizeof int = 4
Size of balls array is 40 bytes.

And my question is: why size of tab is 8 bytes, when size of int is 4 bytes?

  • `tab` isn't an `int`. It is an array, which decays to a pointer, which is size 8. Also, you should use `%zu` (not `%d` or `%ld` or `%zd` all of which you used) to report from `sizeof`. – Weather Vane Oct 13 '21 at 11:07
  • Because on modern CPUs pointers are stored in 8 bytes. – πάντα ῥεῖ Oct 13 '21 at 11:07
  • Also relevant: [When a function has a specific-size array parameter, why is it replaced with a pointer?](https://stackoverflow.com/q/1328223/580083) – Daniel Langr Oct 13 '21 at 11:09
  • See also https://stackoverflow.com/questions/651956/sizeofint-on-x64 – PMF Oct 13 '21 at 11:12
  • on a 64bit machine, cpu, you will get a size 8byte pointer, whence tab is pointer to an array of your choice. –  Oct 13 '21 at 12:18
  • That first line of output is misleading. It should say "Size of tab is 8 bytes". `tab` is not an array. The last line is correct; `balls` is an array, and when its name is used in `sizeof` the name does not decay to a pointer. – Pete Becker Oct 13 '21 at 13:51

0 Answers0