c programming tips and tricks

Arrays and Pointers not Entirely the Same

Many of us tend to misunderstand a concept that pointers and arrays are the same. They are not.

Pointers are merely variables holding the address of some location whereas an array is a contiguous sequence of memory locations.

Pointers can help to create heterogeneous data structures such as a link list or hash table. Whereas the arrays are homogenous which can hold only values of similar type such as numbers and strings.

Pointers get allocated dynamically on the heap whereas the arrays are static allocations on the stack.

At compile time, an array is an array. Only during run-time, an array devolves to a pointer.

To prove this fact, let me show you an example.

int a[10] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int *b = a;

printf("%d\n%d\n", sizeof(a), sizeof(b));

And the output is (assuming size of int is 4 bytes and address size is 8 bytes) –

Leave a Reply

Your email address will not be published. Required fields are marked *