c - "int *nums = {5, 2, 1, 4}" causes a segmentation fault -
int *nums = {5, 2, 1, 4}; printf("%d\n", nums[0]);
causes segfault, whereas
int nums[] = {5, 2, 1, 4}; printf("%d\n", nums[0]);
doesn't. now:
int *nums = {5, 2, 1, 4}; printf("%d\n", nums);
prints 5.
based on this, have conjectured array initialization notation, {}, blindly loads data whatever variable on left. when int[], array filled desired. when int*, pointer filled 5, , memory locations after pointer stored filled 2, 1, , 4. nums[0] attempts deref 5, causing segfault.
if i'm wrong, please correct me. , if i'm correct, please elaborate, because don't understand why array initializers work way do.
there (stupid) rule in c saying plain variable may initialized brace-enclosed initializer list, if array.
for example can write int x = {0};
, equivalent int x = 0;
.
so when write int *nums = {5, 2, 1, 4};
giving initializer list single pointer variable. however, 1 single variable assigned first value 5, rest of list ignored (actually don't think code excess initializers should compile strict compiler) - not written memory @ all. code equivalent int *nums = 5;
. means, nums
should point @ address 5
.
at point should have gotten 2 compiler warnings/errors:
- assigning integer pointer without cast.
- excess elements in initializer list.
and of course code crash , burn since 5
not valid address allowed dereference nums[0]
.
as side note, should printf
pointer addresses %p
specifier or otherwise invoking undefined behavior.
i'm not quite sure trying here, if want set pointer point @ array, should do:
int nums[] = {5, 2, 1, 4}; int* ptr = nums; // or equivalent: int* ptr = (int[]){5, 2, 1, 4};
or if want create array of pointers:
int* ptr[] = { /* whatever makes sense here */ };
edit
after research can "excess elements initializer list" indeed not valid c - gcc extension.
the standard 6.7.9 initialization says (emphasis mine):
2 no initializer shall attempt provide value object not contained within entity being initialized.
/--/
11 the initializer scalar shall single expression, optionally enclosed in braces. initial value of object of expression (after conversion); same type constraints , conversions simple assignment apply, taking type of scalar unqualified version of declared type.
"scalar type" standard term referring single variables not of array, struct or union type (those called "aggregate type").
so in plain english standard says: "when initialize variable, feel free toss in braces around initializer expression, because can."
Comments
Post a Comment