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

前端 未结 7 818
余生分开走
余生分开走 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:49

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

    Each case of arr has sizeof(int) size (which may be 4 on your implementation).

    Since ptr is a pointer to char, pointer arithmetic makes ptr + 4 points 4 bytes after &arr[0], which may be &arr[1].

    In memory, it looks like something like:

    Address | 0 1 2 3 | 4 5 6 7 | ...
    Value   |  arr[0] |  arr[1] | ...
    

提交回复
热议问题