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.
1) Array name gives address of first element of array.
Consider the following program for example.
Value of first element is 10
2) 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
3) Array parameters are always passed as pointers, even when we use square brackets.
sizeof(ptr) = 8 *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
- Pointers in C and C++ | Set 1 (Introduction, Arithmetic and Array)
- Arrays in C Language | Set 2 (Properties)
- How arrays are passed to functions in C/C++
- Arrays in C/C++
- How to pass a 2D array as a parameter in C?
- How to dynamically allocate a 2D array in C?
- C Language Introduction
- Commonly Asked C Programming Interview Questions | Set 2
- Commonly Asked C Programming Interview Questions | Set 1
- Understanding "volatile" qualifier in C | Set 2 (Examples)
- What is the difference between single quoted and double quoted declaration of char array?
- Storage for Strings in C
- Pointer vs Array in C
- Why C treats array parameters as pointers?
- Implement Your Own sizeof