0

I am doing some exercises to figure out how to access values in an array after they are changed with pointers. Can someone point out why the first output does not show the desired output? I am trying to get both cout to print 1234, one by using the new pointer and one by using the position in the array

int main()
{
    char myArray[50]={0};
    short* sizeOfAlloc=(short*)(myArray+5);  
         *sizeOfAlloc=1234;

    cout << (short*)(myArray+5) <<endl; 
    cout << *sizeOfAlloc <<endl;
    system("pause");

}
3
  • In the first line, you don't dereference. Commented Apr 4, 2013 at 22:53
  • myArray is a char** but you cast it to a short*. 2 problems: 1. (the main one), you have changed the level of indirection. 2. You have cast from char to short, which you should only do if you really know what you're doing (more likely you want to cast to int16_t) Commented Apr 4, 2013 at 22:55
  • Thank you Daniel and Dave. Regarding your first comment dave, do you know of a better way to convert some chars to a double or something else? Commented Apr 4, 2013 at 22:58

1 Answer 1

2
cout << (short*)(myArray+5) <<endl; 

Prints the pointer. Not the value pointed by it.

cout << *((short*)(myArray+5)) <<endl;
        ^^                   ^^

Will print the value pointed to by (short*)(myArray+5)

Sign up to request clarification or add additional context in comments.

3 Comments

@stardust_: If this helped resolve your issue, mark this as the answer.
@ViteFalcon How? :) he asked the question. Not me :)
@stardust_: I meant user2012481. Sorry :)

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.