How to convert int* to int

前端 未结 7 994
无人共我
无人共我 2020-12-30 01:29

Given a pointer to int, how can I obtain the actual int?

I don\'t know if this is possible or not, but can someone please advise me?

7条回答
  •  忘掉有多难
    2020-12-30 01:47

    You should differentiate strictly what you want: cast or dereference?

      int x = 5;
      int* p = &x;    // pointer points to a location.
      int a = *p;     // dereference, a == 5
      int b = (int)p; //cast, b == ...some big number, which is the memory location where x is stored.
    

    You can still assign int directly to a pointer, just don't dereference it unless you really know what you're doing.

      int* p = (int*) 5;
      int a = *p;      // crash/segfault, you are not authorized to read that mem location.
      int b = (int)p;  // now b==5
    

    You can do without the explicit casts (int), (int*), but you will most likely get compiler warnings.

提交回复
热议问题