+ 1
Question about Pointer in C
#include <stdio.h> int main() { int arr[5] = {1,2,3,4,5}; int *x = NULL; x = &arr; for (int i = 0; i<5; i++){ printf("%x\n", arr+i); } return 0; } This one gives me 5 addresses, but I’m not sure when they mean. Is it the address of each elements in arr? If that’s true then why does it increment by 4 but not 1 as I defined in for loop? arr(array name) is basically &(arr[0]). (If i understood the lesson correctly) So it should print &(arr[0]) + 0, 1 , 2 , 3 , 4, right?
2 Respuestas
+ 4
Yes each increases by the size of the type in your case int
Address to arr[0] =
Memory location of the first bit in your int array, which has 4 bytes (0000000000000000000000000000000)
Address to arr[1] = Memory location of first bit in your second int in the array, which has another 4 bytes.
... Continues to last element in array.
Some machines however may have a different size in bytes of type integer.
The steps will be determined by the size of the type of element in your array.
Try that same code but change int to char, then long, then float, etc.
Hope this helps you visualize it.
Also in your code you can remove the int* x and x = those lines are not being used for anything in your code.
+ 2
int arr[5] = {1,2,3,4,5};
for (int i = 0; i<5; i++) printf("%d \n", arr[i]);