Pointer type cast?

Lets say I have

 
unsigned long * MyPt; // long=4 bytes 


I need to create a pointer that is type short=1byte and points to the Nth byte in MyPt? Then write 0x12 to that byte.

1
2
3
4
5
6
7
8
unsigned long * MyPt; // long=4 bytes
unsigned short *MyBytePt; 
unsigned int N = 2;

MyPt = 0x0010;
MyBytePt = MyPt+N;
*MyBytePt = 0x12;


This doesn't seem to work and I get "Illegal pointer conversion" during compilation.
What am I doing wrong?
Thank you,

Boris.
the cast you're looking for is reinterpret_cast: http://en.cppreference.com/w/cpp/language/reinterpret_cast

short is not 1 byte, it's usually 2 bytes. One byte is char (and its signed/unsigned variants), which just happens to be the types for which the result of such cast is legal to access.

long is also not necessarily 4 bytes, e.g. it is 8 on the platform I'm using:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
int main()
{
    unsigned long data = 0x0010;
    unsigned int N = 2;

    unsigned long* MyPt = &data;
    unsigned char* MyBytePt = reinterpret_cast<unsigned char*>(MyPt);
    MyBytePt[N] = 0x12;


    std::cout << "size of long is " << sizeof data  << '\n'
              << std::hex << std::showbase << *MyPt << '\n';
}


$ ./test
size of long is 8
0x120000000010


(your output is likely to be 0x120010 on a PC: http://coliru.stacked-crooked.com/a/1296bdc8781df8eb )
Last edited on
Topic archived. No new replies allowed.