问题
So, in C, this perfectly works:
int myArray[] = {1, 2, 3};
why does the following give me a runtime error when accessing an element?
int * myArray2 = {1, 2, 3};
myArray2[0];
when myArray2[0]
basically means *myArray2
, which does also not work?
回答1:
I think that the fundamental difference is that declaring an array implicitly allocates memory, while declaring a pointer does not.
int myArray[3];
declares an array and allocates enough memory for 3 int
values.
int myArray[] = {1,2,3};
is a little syntactic sugar that lets the size of the array be determined by the initialization values. The end result, in terms of memory allocation, is the same as the previous example.
int *myArray;
declares a pointer to an int
value. It does not allocate any memory for the storage of the int
value.
int *myArray = {1,2,3};
is not supported syntax as far as I know. I would expect you would get a compiler error for this. (But I haven't done actual C coding in years.) Even if the compiler lets it through, the assignment fails because there is no memory allocated to store the values.
While you can deference a pointer variable using array syntax, this will only work if you have allocated memory and assigned its address to the pointer.
回答2:
Pointer and Array are different. One difference between them is the subject of your question. When you define an array with the specified size, you have enough memory to initialize it.
However, in the pointer, you should allocate the memory to initialize it. Hence, you should first allocate the memory using a function like malloc
and point the pointer to the allocated memory. Therefore, the problem with the second code is you want to access the part of the memory which is not allocated.
You can correct it likes the following:
int *myarray2 = malloc(3*sizeof(int));
myarray2[0] = 1;
myarray2[1] = 2;
myarray2[2] = 3;
来源:https://stackoverflow.com/questions/49041099/initializing-array-pointer-with-values