首页 > 解决方案 > Difference in printing out pointer value vs array

问题描述

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

标签: c

解决方案


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++;
    }

推荐阅读