I have a question on printing out pointer value and array.
int arr[5] = { 1, 2, 3, 4, 5 };
int * ptr = arr;
for (int i = 0; i < 5; i++) {
(*ptr) += 2;
ptr++;
printf("%d", (*ptr));
}
Above is what I typed in first but it didn't work. So I erased the printf line and entered a new code which is this. And it worked.
for (int i = 0; i < 5; i++) {
printf("%d ", arr[i]);
}
I understand why the second one worked but still don't understand why first one didn't.
Expected output was 3 4 5 6 7 but the actual output of the first code was 2 3 4 5 -858993460
int arr[5] = { 1, 2, 3, 4, 5 };
int * ptr = arr;
for (int i = 0; i < 5; i++) {
(*ptr) += 2;
ptr++;
printf("%d", (*ptr));
}
The reason is you are incrementing the pointer first and then printing its content.
Perhaps you need to print the contents first then increment it to point next element.
int arr[5] = { 1, 2, 3, 4, 5 };
int * ptr = arr;
for (int i = 0; i < 5; i++) {
(*ptr) += 2;
printf("%d", (*ptr));
ptr++;
}
The reason for your error is the fact that you make ptr point to the next value before printing your current value(the value you actually want to be printed). Let's consider the first step of your for loop, line by line, and keep in mind that in the beginning you made ptr point to the first element of the array(int * ptr = arr;):
I hope you understand what happens in the next steps of your for loop.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With