Character pointers and integer pointers (++)

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

    Pointer increment always increases the address it points to by the size of the type represented by it. So, for char pointer it increments by 1 and for integer by 4. But, pointer variable itself will require 4 bytes to hold the address.

    You can inturn think of how array indexing works. Incase of an integer array a[0] will point to first element and a[1] will point to second. In this case for increment of 1 it should increment by 4 bytes to access the next integer. In case of characters it has to be 1. The same concept works for all pointer arithemtic.

    0 讨论(0)
  • 2020-11-29 12:25

    A char is 1 byte, an int is (typically) 4 bytes. When you increment a pointer, you increment by the size of the data being pointed to. So, when you increment a char*, you increment by 1 byte, but when you increment an int*, you increment 4 bytes.

    0 讨论(0)
  • 2020-11-29 12:30

    Simple. It depends upon the compiler.

    If int has 4 bytes of size when you add 1 to its pointer, it will add its size to it, that is, for and if int is of 2 bytes then it will add 2 that is the size into a pointer. For example, in Turbo C++

    int *str = NULL;
    str + 1;    //It will add 2 as Turbo C++ has int size 2 bytes
    

    In Visual C++, str+1; //It will add 4 as Visual C++ has int size 4 bytes.

    And the same is the case with char.

    0 讨论(0)
  • 2020-11-29 12:35

    Simple, in the provided scenario:

    • char is 1 byte long
    • int (in your platform) is 4 bytes long

    The ++ operator increments the pointer by the size of the pointed type.

    0 讨论(0)
提交回复
热议问题