Character pointers and integer pointers (++)

前端 未结 10 1392
终归单人心
终归单人心 2020-11-29 11:50

I have two pointers,

char *str1;
int *str2;

If I look at the size of both the pointers let’s assume

str1=4 bytes
str2=4 byt         


        
10条回答
  •  青春惊慌失措
    2020-11-29 12:17

    A pointer is an abstraction that allows you to reference data in memory so that the raw memory is accessed as an atomic unit to ensure it interpreted appropriately for the type chosen.

    A pointer itself is represented by the native machine word size. In your example, you have two pointers to different types, but they are still both pointers to addresses in memory and hence that is why they are the same size. As mentioned in other answers, to obtain the size of the data type referred to by the pointer, you have to dereference it in the sizeof operation e.g. sizeof(*p).

    The ++ operator allows you to obtain a pointer that references the next address in memory for the appropriate type. If it simply incremented the address by one byte for all types you could end up with an address in memory that points into the middle of a data representation

    e.g. for two unsigned 4-byte integers representing decimal values of 1 and 4,278,190,080 respectively, starting at address 0x00 in memory (note the address here are just for illustration and not representative of a real system since the OS would reserve them for it's own purposes)

    address                          0x00  0x01  0x02  0x03  |  0x04 0x05 0x06 0x07
    data value (4 byte integer)      0x00  0x00  0x00  0x01  |  0xFF 0x00 0x00 0x00
    

    If a pointer to integer has a reference to address 0x00 and operator ++ just incremented the pointer address by 1 byte, you would have a pointer to address 0x01 which if you then accessed that address (plus the subsequent 3 bytes) as an integer you would get an integer that is represent by the data bytes 0x00 0x00 0x01 plus the value of address 0x04 which in this case is the value 0xFF. This would lead to an integer with a decimal value of 511 which is does not represent either of the 2 integers stored in memory.

    To correctly access the next integer in memory, operator ++ has to increment the byte address of the pointer by 4 bytes.

提交回复
热议问题