为什么我不能从int星到虚空星,然后再打字到int64_t星
Why can I not typecast from int star to void star and then to int64_t star?
我有以下代码,运行时会产生垃圾值输出:
#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
这是为什么呢?似乎在 int
和 int64_t
之间进行转换很好:如何将 int 转换为 int64_t。这是由于指针吗?
仅将指针强制转换为另一种类型不会更改原始指针指向的值。您只能安全强制转换值,而不能安全转换指针。
当您看到您的铸造力从索引x[1]
读取其他int
值并将其显示为int64_t
时。
不要在函数中强制转换指针 - 转换值,然后它就可以工作了。
相关文章:
- 从不同线程使用int64的不同字节安全吗
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 如何声明特征矩阵,然后通过嵌套循环初始化它
- 这是我尝试让用户将值输入到数组中.然后将其隐藏为大量的星号
- boost::asio如何生成多个协同程序,然后加入它们
- 如何将图像传输到c++(dll)中的缓冲区,然后在c#的缓冲区中读/写
- 在std::thread中,joinable()然后join()线程安全吗
- C++:如何读取分离变量,然后读取向量
- 为什么我的递归函数按降序打印,然后按升序打印?
- 等待整个 omp 块完成,然后再调用第二个函数
- CMake:如何将库 A 链接到库 B,然后将可执行文件链接到库 A
- 如何存储用户输入的所有数据,然后在他们想要查看所有数据时显示它们
- '{'标记之前的预期类名,然后在预声明时无效使用不完整的类型'class class_name'
- 如何使变量从 x 到 y,然后从 y 返回到 x 并始终重复该过程
- 我有一个数组,我想输入一个范围,然后找到范围内所有偶数的总和?
- 如何正确地推回然后遍历堆中对象的向量?
- 我似乎无法为指针分配一个数组,然后更改数组的内容
- 如何在字符串中找到字符,然后在C++中提取其余的字符串
- 首先按给定顺序打印所有数字,然后使用 Array 打印所有字符和其他符号
- 将加密消息从 php 发送到 C++ 应用程序,然后使用 CryptoPP 进行解密