1

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};
6
  • 4
    You can't loop-initialize your dynamic array because.... ? Commented Nov 18, 2012 at 19:18
  • I cannot use any looping to init the array - why not? Commented Nov 18, 2012 at 19:22
  • 2
    StackOverflow Rule of Thumb #3 is in effect: "If the OP says 'I know', they don't." Commented Nov 18, 2012 at 19:50
  • x[0]=0; x[1]=1; x[2]=2;... Look ma, no loops! Commented Nov 18, 2012 at 20:17
  • 1
    int *x = malloc(sizeof(int)*100); and int x[100]; are not the same, and not just because of stack and heap. Commented Nov 18, 2012 at 20:21

3 Answers 3

2

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];.

Sign up to request clarification or add additional context in comments.

2 Comments

Are there cases where a cannot be treated like b? This is with the exception of functions like free() and realloc(), or it being potentially unsafe to pass pointers to a.
@Paul: Sure: int n; p = &n; is valid, but a = &n; is not. Array decay produces "rvalues" (if that makes sense). Also, &p has type int**, while &a has type (int*)[3].
0

If you cannot initialize the array with looping, you can use memset() and get away with it.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.