C array malloc() VS {}

I know that the result of

int *x = malloc(sizeof(int)*100);

and

int x[100];

is same,but the first one is allocating heap memory,and second one is allocating stack memory.

Now i need to create a huge array(about 10000 element,not in a pattern),I think malloc() is more suitable.

But when i ready to initialize the array, I face a problem. I cannot use any looping to init the array,how can I init an array that created by using malloc ,just like using

int x[100] = {1,2,3,4,......,6,7,5};

When you say int a[] = { 1, 2, 3 }; , you are using an initializer to provide the initial data for (and infer the size of) the array a . This is part of the grammar of C.

When you say int * p = malloc(1000); , you are simply making a library call and storing a pointer. There is no mechanism in the language or library to provide initial values for the memory to which this pointer points, nor is it required that the pointer point to anything (it may be NULL ).

You should notice that arrays are not pointers, and pointers are not arrays. a and p are entirely different animals, notwithstanding the fact that you can say p[1] = a[1]; .


如果你不能用循环来初始化数组,你可以使用memset()并且避开它。


If the data doesn't change, the best way is to write

static const int x [100] = { 23, 12, 5, 7, ... };

No code. No time needed for initialisation. I have actually seen code that initialised megabytes of data that way, with no problems.

链接地址: http://www.djcxy.com/p/80440.html

上一篇: c自定义内存区域的malloc功能

下一篇: C数组malloc()VS {}