C Pointers and Arrays
In C, pointers and arrays are very closely related. The name of an array is the address of its first element.
Array name as pointer
#include <stdio.h>
int main(void) {
int a[] = {10, 20, 30};
printf("%d\n", *a); // a[0]
printf("%d\n", *(a + 1)); // a[1]
printf("%d\n", *(a + 2)); // a[2]
return 0;
}
Output:
Output of the above program is
10
20
30
The expression a[i] is exactly the same as *(a + i). The compiler converts the first form to the second.
Store the array address in a pointer
#include <stdio.h>
int main(void) {
int a[] = {10, 20, 30};
int *p = a;
for (int i = 0; i < 3; i++) {
printf("%d %d\n", p[i], *(p + i));
}
return 0;
}
Output:
Output of the above program is
10 10
20 20
30 30
Difference between array and pointer
| Array | Pointer |
|---|---|
| Fixed block of memory | Variable that stores an address |
sizeof(a) is the whole array | sizeof(p) is size of the pointer |
Cannot be changed to point somewhere else (a++ is an error) | Can point to any place (p++ is fine) |
#include <stdio.h>
int main(void) {
int a[5] = {1, 2, 3, 4, 5};
int *p = a;
printf("%zu\n", sizeof(a));
printf("%zu\n", sizeof(p));
return 0;
}
Output:
Output of the above program is
20
8
Note:
The second number is the pointer size on a 64 bit system. When an array is passed to a function, it becomes a pointer, so the function does not know its size.
Next: C Pointers and Functions.
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |