Initializing array (pointer) with values [duplicate]

独自空忆成欢 提交于 2020-06-04 02:03:50

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!