Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confusion between "int array[int]" and "int *array"

int array[100];

int *array;

I am confused about the differences between int array[100] and int *array.

Essentially, when I do int array[100] (100 it's just an example of an int), I just reserved space in memory for 100 ints, but I can do int * array and I didn't specify any type of size for this array, but I can still do array[9999] = 30 and that will still make sense.

So what's the difference between these two?

like image 545
Joao Parente Avatar asked Jan 24 '19 11:01

Joao Parente


2 Answers

A pointer is a pointer, it points somewhere else (like the first element of an array). The compiler doesn't have any information about where it might point or the size of the data it might point to.

An array is, well, an array of a number of consecutive elements of the same type. The compiler knows its size, since it's always specified (although sometimes the size is only implicitly specified).

An array can be initialized, but not assigned to. Arrays also often decay to pointers to their first element.

Array decay example:

int array[10];

int *pointer = array;  // Here the symbol array decays to the expression &array[0]

// Now the variable pointer is pointing to the first element of array

Arrays can't naturally be passed to function. When you declare a function argument like int arr[], the compiler will be translating it as int *arr.

All of this information, and more, should be in any good book, tutorial or class.

like image 74
Some programmer dude Avatar answered Oct 29 '22 10:10

Some programmer dude


The difference is when you do int array[100], a memory block of 100 * sizeof(int) is allocated on the stack, but when you do int *array, you need to dynamically allocate memory (with malloc function for example) to use the array variable. Dynamically allocated memory is on the heap, not stack.

like image 45
Leo Avatar answered Oct 29 '22 10:10

Leo