简体   繁体   中英

What is the difference between malloc and array

I want to ask about malloc and array.

int *x;

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

and

int x[4];

what is the difference between them?

The most important difference between int *xp; and int xa[4]; is sizeof(xp) != sizeof(xa) the size of the declared object.

You can pass the xa object as int *pparam to a function, but you cannot pass xp as a int aparam[4] to a function, as aparam describes the whole 4 int object and pparam describes a pointer to an object that might have any length.

Also xa will be reserved in the data area of the linked program, while the pointer malloc(sizeof(int)*4) will be allocated by a system call at runtime and on the heap. Check the vast address difference in a debugger!

Well, there are multiple differences.

This allocates a buffer of one int on the heap...

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

And this allocates an array of four int s either on the stack or in global memory, or perhaps declares it as a member of a struct or class, if it appears within the definition of a struct or class...

int x[4];

Other than the location of the allocations, the first allocated space for one int and the second allocated space for four int s. But assuming you meant to do this instead...

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

...then in that case, both allocations are a block of memory that is four times the size of an int on your platform. And from a usage standpoint, you can then use them both in pretty much the same way; x[0] is the first int in either case, and since neither are declared const , you can read or write to either in the same way.

So now we get to the difference in the allocation characteristics & lifetime of the two different ways of allocating that memory:

In the malloc() 'ed case, memory for that request is allocated on the heap, and its lifetime is however long you want to keep it until you call free() on it. In the other case, if you declared it as a local variable inside a method/function, its lifetime is until program execution exits the scope in which it was declared. If you declared it as a global variable, its lifetime is the lifetime of the entire application. And if you declared it as a member variable of a struct or class, then its lifetime is that of its enclosing struct/class, whatever that may be.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM