Understand the difference between:
int*(pointer to element)int (*)[N](pointer to entire array)int* a[N](array of pointers)
These three forms are often mixed up, but they have different types and memory behavior.
int* p = nums;points tonums[0].int (*pa)[4] = &nums;points to the wholenumsarray.p + 1moves bysizeof(int).pa + 1moves bysizeof(nums)(the whole array block).int* ptr_array[3]is an array where each slot stores an address.
File: 12_pointer_to_array_vs_array_of_pointers.cpp
numsis declared asint[4].elem_ptrandarray_ptrare created with different pointer types.- The program prints addresses:
numsandelem_ptrrepresent the first element address.&numsis the address of the array object.
- The program prints
elem_ptr + 1andarray_ptr + 1:- the first advances by one element,
- the second advances by one entire array.
multiply_all(array_ptr, 2)shows how a function can explicitly receive a pointer to an array of fixed size.- Finally,
ptr_arraydemonstrates an array whose elements are pointers.
- Writing
int* p[4]when you actually wantedint (*p)[4]. - Assuming
&numshas typeint*(it does not). - Forgetting that pointer arithmetic depends on the pointer type.
- Change
numsto size 6 and update the type ofarray_ptr. - Add another function that receives
int*+ size and compare it with the pointer-to-array version. - Replace
int* ptr_array[3]withconst char* words[3]and print each string.
g++ -std=c++20 -O2 -Wall -Wextra -pedantic -g 12_pointer_to_array_vs_array_of_pointers.cpp -o app
./app