Pointers and Arrays
Get to learn how C uses pointers to reference arrays.
We'll cover the following
Arrays under the hood
When we declare an array using an expression like int vec[5];
, what is really happening behind the scenes, is that a block of memory is being allocated (on the stack in this case) large enough to hold five integers, and the vec
variable is a pointer that points to the first element in the array. When we index into the array with an expression like printf("vec[2] = %d\n", vec[2]);
what is really happening is that C is using pointer arithmetic to step into the array an appropriate number of times, and reading the value in the memory location it ends up in. So, if we ask for the third element of the vec
array using vec[2]
then C is first looking at the location pointed to by vec
(the first element of the array), stepping two integers forward, and then reading the value it finds there (the value in vec[2]
).
We can also use pointer arithmetic to access an array allocated on the heap. To allocate an array on the heap, we can use the functions malloc
or calloc
to be discussed later. For now, we just note that in the code below, an integer array of size 3 is created, by passing the size of the array (in bytes) to malloc
. The function malloc
returns the starting address of the allocated memory. We then use pointer arithmetic to read off the third value:
Create a free account to access the full course.
By signing up, you agree to Educative's Terms of Service and Privacy Policy