Pointers and Arrays

Get to learn how C uses pointers to reference arrays.

When you 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 5 integers, and the vec variable is a pointer that points to the first element in the array. When you 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 the appropriate number of times, and reading the value in the memory location it ends up in. So if you ask for the 3rd3^{rd} 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), and stepping two integers forward, and then reading the value it finds there (vec[2]).

The explicit way of doing this would be to use malloc() or calloc() to allocate the array (in this case on the heap) and then use pointer arithmetic to read off the 3rd3^{rd} value:

Create a free account to access the full course.

By signing up, you agree to Educative's Terms of Service and Privacy Policy