E
E
evg_962018-03-26 18:19:32
C++ / C#
evg_96, 2018-03-26 18:19:32

Why does sizeof show the actual size of an array when the array name is actually a pointer to the first element?

Why is sizeof marbles 40 bytes when marbles is a pointer to the first element of the array? ( printf("%d", marbles == &marbles[0]); // true)
Everything is logical in the sum function, the pointer to the first element is passed to the function, and the size of the pointer is actually displayed, equal to 8 bytes.
why marbles == &marbles[0], but sizeof(marbles) != sizeof &marbles[0]?

#include <stdio.h>
#include <conio.h>

#define SIZE 10

int sum(int * arr, int n);

int main(void)
{
    int marbles[SIZE] = { 20, 10, 5, 39, 4, 16, 19, 26, 31, 20 };
    long answer = sum(marbles, SIZE);

    printf("Common sum of array items = %ld.\n", answer);
    printf("Memory: %zd bytes.\n", sizeof marbles); // 40
    printf("%d", marbles == &marbles[0]); // true

    _getch();

    return 0;
}

int sum(int * arr, int n)
{
    int index;
    int total = 0;
    
    for (index = 0; index < n; index++)
        total += *(arr + index);

    printf("Size of arr = %zd bytes.\n", sizeof arr); // 8

    return total;
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
T
tsarevfs, 2018-03-26
@tsarevfs

In fact, a static array is really a pointer. But the real type is different and the compiler knows the real size of the array. After you cast an array to a pointer type (for example, when passing it to a function), this information is lost and sizeof will already return the size of the pointer.

M
Mercury13, 2018-03-26
@Mercury13

Although an array is often identified with a pointer, an array is NOT a pointer. He, for example, other operations lead to undefined behavior.
And the worst thing about C is that in the code
x is not an array, but a pointer. To have an array, you need C++ And the compiler even highlights that a function parameter marked as an array is always a pointer.

typedef int Arr[SIZE];
int sum(Arr arr, int n)
// warning: 'sizeof' on array function parameter 'arr' will return size of 'int *' [-Wsizeof-array-argument]|

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question