Printing corresponding address of each element of an array.
int main() {
int numbers[5] = {1, 2, 5, 8, 3};
for (int i=0; i<5; i++){
printf("%d = %p\n", numbers[i], &numbers[i]);
}
return 0;
}
Output:
1 = 0x7ffffa8cf140
2 = 0x7ffffa8cf144
5 = 0x7ffffa8cf148
8 = 0x7ffffa8cf14c
3 = 0x7ffffa8cf150
Printing array elements address without index value.
int main() {
int numbers[5] = {1, 2, 5, 8, 3};
printf("Array address: %p", numbers);
return 0;
}
Output:
Array address: 0x7ffcf4fe97c0
- The memory address of the first array element and the address of the array is the same.This is because the address of the array always points to the first element of the array.
- Also in the above code to print the array address we have used only the name of the array instead of the
&
sign. This is because in most context array names are by default converted to pointers and we can directly use name of the array without&
sign.
Print other array elements address without index value
printf("Array address: %p", numbers + 1);
- this will print the second element.
printf("Array address: %p", numbers + 2);
- this will print the third element.
Printing array element's memory address using for loop without index value.
int main() {
int numbers[5] = {1, 2, 5, 8, 3};
for (int i=0; i<5; i++){
printf("%d = %p\n", numbers[i], numbers + i);
}
return 0;
}
Output:
1 = 0x7ffccb8a1d70
2 = 0x7ffccb8a1d74
5 = 0x7ffccb8a1d78
8 = 0x7ffccb8a1d7c
3 = 0x7ffccb8a1d80
Access array element using pointer.
In order to use array elements using pointers, we have to use *(numbers + i)
int main() {
int numbers[5] = {1, 2, 5, 8, 3};
for (int i=0; i<5; i++){
printf("%d = %p\n", *(numbers + i), numbers + i);
}
return 0;
}
Output:
1 = 0x7fff49ac30b0
2 = 0x7fff49ac30b4
5 = 0x7fff49ac30b8
8 = 0x7fff49ac30bc
3 = 0x7fff49ac30c0
*Change array elements using pointers *
int main() {
int numbers[5] = {1, 2, 5, 8, 3};
*numbers = 76;
*(numbers + 1) = 89;
printf("%d ", *numbers);
printf("%d", *(numbers+1));
return 0;
}
Top comments (0)