int c[] = {1, 2, 3, 4, 5};
int *c = malloc(sizeof(int)*5;
c[0] = {1};
c[1] = {2};
c[3] = {3};
c[4] = {4};
c[5] = {5};
这两种开辟数组的方式有什么区别?为什么第一种方式看上去也是动态分配内存的, 却不需要 malloc ?
为什么此处的 malloc 不需要前面显示的声明(int*)
即, int *c = (int*)malloc(sizeof(int)*5;
malloc 返回的不是 void*
吗?
以上, 谢谢.
PS: 我知道这种问题应该多看经典书, 不过现在寒假, 书都在学校, 这个问题涉及到符号问题 google 又不怎么会匹配, 所以来这里请教大家.
高洛峰2017-04-17 15:21:34
In the first method, you have clearly given the several elements of the array in the code. After a little analysis, the compiler can figure out the memory size that needs to be allocated, but it is just passed implicitly. Only 5 of the methods.
The pointer type is given in the second method, which can help the compiler better identify the pointer type. For example, if you later perform array operations on pointers, the compiler will be able to identify the actual memory length of each unit.