Two different outputs using malloc

时间:2015-10-29 15:58:46

标签: c pointers malloc

This is something that's been bugging me for couple of hours now, i'm really frustrated why's this happening, so i'm asking if any good soul could possibly explain this to me.

int main()
{
    FILE* filePointer;
    int* tempPointer1;
    int* tempPointer2;

    filePointer = fopen("numbers.txt","r");

    tempPointer1 = (int*) malloc(sizeof(int)*10);
    tempPointer2 = tempPointer1;

    int j;
    for(j=0;j<10;j++)
    {
        fscanf(filePointer,"%d ",tempPointer1);
        printf("%d ", *tempPointer1);
        tempPointer1+=sizeof(int);
    }

    printf("\n");

    int i;
    for(i=0;i<10;i++)
    {
        printf("%d ", *tempPointer2);
        tempPointer2+=sizeof(int);
    }

    fclose(filePointer);
    return 0;
}

And this is the output that im getting:

1 2 3 4 5 6 7 8 9 10 

1 2 3 12337 5 6 7 8 9 10 

Can anyone explain why?

P.S If i use static int array output is the same.

1 个答案:

答案 0 :(得分:4)

指针运算的设计使得增量具有类型指针的大小。所以在这部分

tempPointer1+=sizeof(int);

您正在增加太大的步骤,超出数组的范围并调用未定义的行为。你需要增加1,即

tempPointer += 1;

或者更简洁地说,

++tempPointer1;

注意:您不应该在C中投射malloc的结果。您可以直接将其分配给非空指针:

tempPointer1 = malloc(sizeof(int)*10);