c - 使用 malloc 的两个不同输出

标签 c pointers malloc

这件事已经困扰我几个小时了,我真的很沮丧为什么会这样,所以我想问问是否有好心人可以向我解释一下。

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

这是我得到的输出:

1 2 3 4 5 6 7 8 9 10 

1 2 3 12337 5 6 7 8 9 10 

谁能解释一下为什么?

P.S 如果我使用 static int 数组输出是相同的。

最佳答案

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

tempPointer1+=sizeof(int);

您递增的步长太大,超出了数组的边界并调用了未定义的行为。您需要增加 1,即

tempPointer += 1;

或者,更简洁地说,

++tempPointer1;

注意:你不应该在 C 中转换 malloc 的结果。你可以将它直接分配给一个非空指针:

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

关于c - 使用 malloc 的两个不同输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33419085/

相关文章:

c - Dart RawSockets 有什么用?

c - 接收C套接字数据分配二维数组

c - malloc 存储它的元数据

c - C 中的基本扫描和打印功能出现问题

C: 不丢失空格的文件解析

c++ - 使用 "ldaps"绑定(bind)到 ldap 服务器

c - 我怎样才能将结构保存在文件中.... C lang

C++ 交换成员数组和关联指针

c++ - 动态内存分配如何在运行时分配内存?

c - dlmalloc 中的 fd 和 bk