我想将int
值保存到一个指针变量中。但是我得到一个错误:
#include <iostream>
using namespace std;
int main()
{
int *NumRecPrinted = NULL;
int no_of_records = 10;
NumRecPrinted = (int*)no_of_records; // <<< Doesn't give value of NumRecPrinted
cout << "NumRecPrinted!" << NumRecPrinted;
return 0;
}
我试过这样做但我得到 0 作为返回:
int main()
{
int demo(int *NumRecPrinted);
int num = 2;
demo(&num);
cout << "NumRecPrinted=" << num; <<<< Prints 0
return 0;
}
int demo (int *NumRecPrinted)
{
int no_of_records = 11;
NumRecPrinted = &no_of_records;
}
NumRecPrinted 返回 0
最佳答案
有时将非指针值“编码”为指针很有用,例如当您需要将数据传递到 pthreads 线程参数 (void*
) 时.
在 C++ 中,你可以通过 hackery 来做到这一点; C 风格的转换是这种黑客行为的一个例子,事实上 your program works as desired :
#include <iostream>
using namespace std;
int main()
{
int *NumRecPrinted = NULL;
int no_of_records = 10;
NumRecPrinted = (int*)no_of_records;
cout << "NumRecPrinted!" << NumRecPrinted; // Output: 0xa (same as 10)
return 0;
}
您只需要意识到 0xa
是十进制 10
的十六进制表示。
然而,这是一个 hack;您不应该能够将 int
转换为指针,因为在general 中它没有任何意义。事实上,即使在 pthreads 情况下,将指针传递给某个封装了您要传递的数据的结构也更加合乎逻辑。
所以,基本上...“不要”。
关于c++ - 将int转换为指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9212219/