0

I'm trying to do something very simple, at least I thought, with no success. I would like to assign the address pointed to by an integer pointer to the address pointed to by a char pointer. Example

//C++

int *pointerint;
char *pointerchar;
pointerchar = pointerint;

//

I've tried to do this severals different ways without success.

Example:

pointerchar = (char *) &pointerint;

The compiler excepts it but the address assigned to the pointer is zero. That can not be correct. Can anyone tell me how to do this correctly and what I am doing wrong. Thanks in advance for all your help.

1
  • 3
    This is indeed very simple to do as you can see from the answers ... but why do you want to do it? It's a generally dangerous operation, especially in the hands a rookie. Commented Sep 26, 2012 at 19:10

2 Answers 2

3

Try (if C):

pointerchar = (char *) pointerint;
Sign up to request clarification or add additional context in comments.

15 Comments

This is correct, but to extend, what you did there is typecasted the address of the pointer. Since pointerint is already a pointer, you don't need to use the & operator again.
Here I convert the value of the pointer and not the address of the pointer (what the OP did).
@LuchianGrigore I assume he initializes the pointerint pointer.
Even if pointerint isn't initialised, it will work. You'd just be copying the number across. All you're changing is the semantic meaning of the data that is pointed to.
@slugonamission a non-initialized pointer is an invalid pointer and accessing (even just reading it) an invalid pointer is undefined behavior.
|
3

Now that you have a C answer, here's a C++ one:

int *pointerint;  
char *pointerchar;
//initialize pointerint
pointerchar = reinterpret_cast<char*>(pointerint);

Note that if you don't initialize the pointerint, you'll run into undefined behavior.

4 Comments

pointers? You mean "if you don't initialize pointerint" ... you just set pointerchar and don't need to initialize it.
@JimBalter true. That's what I meant. :)
I always love C++ answers, :) +1
Yes that's the correct answer, this holds true for C as well, initializing the pointer is key! Also, I need to subtract 3 for the final pointer to start the char pointer at the MSB in the word, byte 0.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.