为什么我不能从int星到虚空星,然后再打字到int64_t星

Why can I not typecast from int star to void star and then to int64_t star?

本文关键字:int64 然后 不能 int 为什么      更新时间:2023-10-16

我有以下代码,运行时会产生垃圾值输出:

#include <iostream>
#include <cstdlib>
#include <stdio.h>
using namespace std;
void printer(void* x, int length, int y){
    if(y == 0){
        int64_t* z = (int64_t*) x;
        for(int i=0;i<length;i++){
            printf("%ldn", z[i]);
        }
    }
}
int main(){
    int length = 4;
    int* x = (int*) malloc(length * sizeof(int));
    int y = 0;
    x[0] = 1;
    x[1] = 4;
    x[2] = 1;
    x[3] = 4;
    printer(x, length, y);
}
Output:
17179869185
17179869185
0
132049

但是,当我在main中将类型从int更改为int64_t时,它可以正常工作:

#include <iostream>
#include <cstdlib>
#include <stdio.h>
using namespace std;
void printer(void* x, int length, int y){
    if(y == 0){
        int64_t* z = (int64_t*) x;
        for(int i=0;i<length;i++){
            printf("%ldn", z[i]);
        }
    }
}
int main(){
    int length = 4;
    int64_t* x = (int64_t*) malloc(length * sizeof(int64_t));
    int y = 0;
    x[0] = 1;
    x[1] = 4;
    x[2] = 1;
    x[3] = 4;
    printer(x, length, y);
}
Output:
1
4
1
4

这是为什么呢?似乎在 intint64_t 之间进行转换很好:如何将 int 转换为 int64_t。这是由于指针吗?

仅将指针强制转换为另一种类型不会更改原始指针指向的值。您只能安全强制转换值,而不能安全转换指针。

当您看到您的铸造力从索引x[1]读取其他int值并将其显示为int64_t 时。

不要在函数中强制转换指针 - 转换值,然后它就可以工作了。

相关文章: