I have a variable x declared as int *x = y, where y is also a pointer variable. Is there any way to store the variable in y to x without making x a pointer such that it would look like:

int x = y;      //y declaration => int *y = thing[4]

Is this confusing?

Recommended Answers

All 3 Replies

What you need to do is dereference the y pointer. There are a couple of ways to do it:

1) the * (star) is a dereference operator when applied to a pointer variable:

int x = *y; //gets the value that y points to.

2) the is a dereference operator that also allows you to get the value at "i" integers from the address stored in y (i.e. this indexes into an array):

int x = y[0];  //gets the value that y points to.
x = y[2];      //gets the value 2 integers after y[0].

What mike said is generally correct. However, it is also dangerous! Never dereference a pointer like this without first making sure it is not a valid pointer. This is why we have reference objects in C++ since it eliminates the need to check the pointer first. IE:

int int_function_1(int* y)
{
   int x = *y; // BAD! If y is null, you are toast!
   return x+1;
}

int int_function_2(int* y)
{
   int x = 0;
   if (y != 0)
   {
       x = *y; // Better - we know that y is not null
   }
   return x + 1;
}

int int_function_3(int& y)
{
    int x = y; // Best - we know that y references a real integer
               // unless the caller of this function was a real meathead!
    return x + 1;
}

Also, in mike's example of doing array references (legal code), this is also dangerous in that you must know two things. First that the memory that y points to is really an array (if we are looking past the 0th element), and second that the array is big enough and properly initialized for the element we are accessing. In any case, this sort of code is a very big security hole.

Thanks mike2000. It worked

And rubberman: your post also helped. I was able to get the code working, but i realized later this method was not the correct way - i didn't need any ynamic arrays to begin with.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.