Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

converting int to pointer

Tags:

c++

pointers

I want to save int value to a pointer variable. But I get an error:

#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;
}

I tried doing this but I get 0 as return:

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 returns as 0

like image 237
AJ. Avatar asked Feb 09 '12 14:02

AJ.


3 Answers

It's sometimes useful to "encode" a non-pointer value into a pointer, for instance when you need to pass data into a pthreads thread argument (void*).

In C++ you can do this by hackery; C-style casts are an example of this hackery, and in fact 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;
}

You just need to realise that 0xa is a hexadecimal representation of the decimal 10.

However, this is a hack; you're not supposed to be able to convert ints to pointers because in general it makes no sense. In fact, even in the pthreads case it's far more logical to pass a pointer to some structure that encapsulates the data you want to pass over.

So, basically... "don't".

like image 145
Lightness Races in Orbit Avatar answered Oct 01 '22 08:10

Lightness Races in Orbit


You want to be doing this:

NumRecPrinted = &no_of_records;

i.e. you're taking the address of no_of_records and assigning it to NumRecPrinted.

And then to print it:

cout << "NumRecPrinted!" << *NumRecPrinted;

i.e. you're dereferencing NumRecPrinted which will get the int stored at the memory address pointed to by NumRecPrinted.

like image 30
mattjgalloway Avatar answered Oct 01 '22 10:10

mattjgalloway


#include <iostream>
using namespace std;

int main()
{
int *NumRecPrinted = NULL; // assign pointer NumRecPrinted to be valued as NULL
int *NumRecPrinted2 = NULL;
int no_of_records = 10; // initialize the value of the identificator no_of_records 
NumRecPrinted = (int*)no_of_records; // sets a pointer to the address no_of_records
NumRecPrinted2 = &no_of_records; // gives a pointer to the value of no_of_records

cout << "NumRecPrinted!" << NumRecPrinted;  // address of no_of_records 0000000A
cout << "NumRecPrinted!" << *NumRecPrinted2; // value of no_of_records 10
system("pause"); // ninja 
return 0;
}
like image 21
Dzek Trek Avatar answered Oct 01 '22 09:10

Dzek Trek