c++ - 将int转换为指针

标签 c++ pointers

我想将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/

相关文章:

c++ - 如何在运行时为虚函数获取指针的确切类型?

c++ - 使用带有指向数据成员的指针的全局命名空间限定符

c++ - 如何读取数据构造一个const数组?

pointers - 如何用cython包装一个参数为wchar_t指针的C函数

c++ - 指针 : p++ & p+1

c++ - 自动绑定(bind)到 lambda 函数的生命周期是多少?

c++ - 如何重置 std::condition_variable

c++ - 防止 Content-Disposition 中的绝对文件路径 "filename"

c++ - 从基本模板对方法的调用无法编译

c - 是否可以使用指向 char (char **pptr_char) 的指针来存储动态数量的动态大小字符串?