Pointers are used for storing address of dynamically allocated arrays and for arrays which are passed as arguments to functions. In other contexts, arrays and pointer are two different things, see the following programs to justify this statement.
Behavior of sizeof operator
Size of arr 24 Size of ptr 8
Assigning any address to an array variable is not allowed.
Compiler Error: incompatible types when assigning to type 'int' from type 'int *'
See the previous post on this topic for more differences.
Although array and pointer are different things, following properties of array make them look similar.
- Array name gives address of first element of array.
Consider the following program for example.
Value of first element is 10
Array members are accessed using pointer arithmetic.
Compiler uses pointer arithmetic to access array element. For example, an expression like “arr[i]” is treated as *(arr + i) by the compiler. That is why the expressions like *(arr + i) work for array arr, and expressions like ptr[i] also work for pointer ptr.
arr = 30 *(arr + 2) = 30 ptr = 30 *(ptr + 2) = 30
Array parameters are always passed as pointers, even when we use square brackets.
sizeof(arr) = 24 sizeof(ptr) = 4 *ptr = 10
Please refer Pointer vs Array in C for more details.
This article is contributed by Abhay Rathi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Double Pointer (Pointer to Pointer) in C
- Pointer to an Array | Array Pointer
- What is a Pointer to a Null pointer
- Difference between pointer to an array and array of pointers
- Pointer vs Array in C
- Sum of array using pointer arithmetic
- Reference to a pointer in C++ with examples and applications
- How to declare a pointer to a function?
- 'this' pointer in C++
- Multidimensional Pointer Arithmetic in C/C++
- When do we pass arguments by reference or pointer?
- How to write C functions that modify head pointer of a Linked List?
- Function Pointer in C
- Opaque Pointer
- Passing by pointer Vs Passing by Reference in C++
- void pointer in C / C++
- NULL pointer in C
- C | Pointer Basics | Question 1
- C | Pointer Basics | Question 2
- C | Pointer Basics | Question 3