Character pointers and integer pointers (++)

前端 未结 10 1393
终归单人心
终归单人心 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:18

    Pointer actualy holds the address of the memory location, which is 4bytes integer. str1 points to a location that holds 1byte, so if you increase the address of the str1 it jumps to next address of 1byte data. But in other case, str2 points to a 4byte data, so if you increase that address, it must jump over that data to get to the next 4byte data, so it incremets by 4.

    This is how 1 byte sequence of data is stored in memmory:

    ADDRESS:         FF334400  FF334401  FF334402  FF334403
    DATA (1BYTE):           1         2         3         4
    

    So if str1 wants to point to the number 2, it must hold its address, which is FF334401. If you increase str1, it must jump over the 2s address and get to 3, and to do that it must be incremented by 1.

    In other case:

    ADDRESS:         FF334400  FF334401  FF334402  FF334403 FF334404 ... FF334407
    DATA (4BYTE):           0         0         0         1        0            2
    

    Now if str2 points to the number 1 which is integer, and it actualy is 4byte data, it points to the begining of that data, which is address FF334400. When you increase it, it must jump over all 4 bytes of the 1s data to get to the 2s data, so it increases by 4 and its address becomes FF334404 which is the first byte of the 4byte data of the number 2.

提交回复
热议问题