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

后端 未结 5 585
情书的邮戳
情书的邮戳 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 04:53

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

    nums is a pointer of type int. So you should make this point to some valid memory location. num[0] you are trying to dereference some random memory location and hence the segmentation fault.

    Yes the pointer is holding value 5 and you are trying to dereference it which is undefined behavior on your system. (Looks like 5 is not a valid memory location on your system)

    Whereas

    int nums[] = {1,2,3,4};
    

    is a valid declaration where you are saying nums is an array of type int and memory is allocated based on number of elements passed during initialization.

提交回复
热议问题