【问题标题】:Pointer to int. C++指向 int 的指针。 C++
【发布时间】:2011-03-10 07:13:02
【问题描述】:

我需要将函数指针传递给 int。 现在,如果我想通过 5,我会这样做:

int * i = NULL;
int b = 5;
i = &b;

有没有更好的写法?

我想将 i int 中的字节传递给这个函数:

void Write2Asm(void* pxAddress, BYTE * MyBytes,  int size)

【问题讨论】:

  • @Hooch 而不是 Null 您应该考虑使用 nullptr - 它是标准。
  • 也许我错过了什么,但这样做有什么问题:int i = 5; func(&i);?
  • @Hooch 我知道这“只是”一个措辞,但我认为这很重要:你没有通过 5,你正在做的是传递 变量的地址 恰好有 5 个值。
  • nullptr 还不是标准的。
  • “与新标准保持同步”不需要使用nullptr。 “传统”的方式哪儿也去不了。

标签: c++ pointers int


【解决方案1】:

你可以将 &b 传递给函数;不需要中间指针变量。

【讨论】:

  • 还有一个问题。我可以使用 (PBYTE)&i where int i = 5。函数真的需要指向字节的指针
  • @Hooch:当然。你可以这样做。
【解决方案2】:

为什么要创建指针变量?为什么不能这样呢?

int b = 5;
func(&b)

【讨论】:

    【解决方案3】:
    void f(int *i)
    {
      //...
    }
    
    int b = 5;
    f(&b);
    

    够了!

    【讨论】:

      【解决方案4】:

      有一些旧的 C API 总是通过指针获取参数,即使它们实际上是只读布尔值等。我不推荐它 - 更多是为了兴趣 - 但如果你想了解整个猪你可以做一些骇人听闻的事情,比如:

      #include <iostream>
      
      struct X
      {
          X(int n) : n_(n) { std::cout << "X()\n"; }
          ~X() { std::cout << "~X()\n"; }
          operator int&() { return n_; }
          operator const int() const { return n_; }
          int* operator&() { return &n_; }
          const int* operator&() const { return &n_; }
          int n_;
      };
      
      // for a function that modifies arguments like this you'd typically
      // want to use the modified values afterwards, so wouldn't use
      // temporaries in the caller, but just to prove this more difficult
      // case is also possible and safe...
      void f(int* p1, int* p2)
      {
          std::cout << "> f(&" << *p1 << ", &" << *p2 << ")\n";
          *p1 += *p2;
          *p2 += *p1;
          std::cout << "< f() &" << *p1 << ", &" << *p2 << "\n";
      }
      
      int main()
      {
          // usage...
          f(&X(5), &X(7));
      
          std::cout << "post\n";
      }
      

      至关重要的是,这些临时变量在函数调用 f(...) 退出之前一直有效。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-09-10
        • 2017-06-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多