“int *nums = {5, 2, 1, 4}” causes a segmentation fault

后端 未结 5 586
情书的邮戳
情书的邮戳 2020-11-29 04:20
int *nums = {5, 2, 1, 4};
printf(\"%d\\n\", nums[0]);

causes a segfault, whereas

int nums[] = {5, 2, 1, 4};
printf(\"%d\\n\", nums[         


        
5条回答
  •  臣服心动
    2020-11-29 05:06

    By assigning {5, 2, 1, 4}

    int *nums = {5, 2, 1, 4};
    

    you are assigning 5 to nums (after an implicit typecast from int to pointer to int). Dereferring it makes an access call to memory location at 0x5. That might not be allowed for your program to access.

    Try

    printf("%p", (void *)nums);
    

提交回复
热议问题