My char pointer points to invalid value after being cast from int*

前端 未结 7 676
余生分开走
余生分开走 2021-02-03 17:19

I am learning C programming language, I have just started learning arrays with pointers. I have problem in this question, I hope the that output must be

7条回答
  •  情书的邮戳
    2021-02-03 17:53

    int main(){
     int arr[] = {1,2,3,4,5};
     char *ptr = (char *) arr;
     printf("%d",*(ptr+4));
     return 0;
    }
    

    Imagine arr is stored at the address 100 (totally dumb address). So you have: arr[0] is stored at the address 100. arr[1] is stored at the address 104. (there's is +4 because of the type int) arr[2] is stored at the address 108. arr[3] is stored at the address 112. Etc etc.

    Now you're doing char *ptr = (char *) arr;, so ptr = 100 (the same as arr). The next statement is interesting, specially the second argument of printf : *(ptr+4). Keep in my mind that ptr = 100. So ptr + 4 = 104, the same address that arr[1] ! So it will print the value of arr[1], which is 2.

提交回复
热议问题