简体   繁体   中英

memory allocation vs array size definition

In C, for example anytime I wanna deal with strings (which C does not support), I can do either

 char* String = (char*) malloc(25);

Or

 char String[25];

I'd like to know what the main difference between these two ways of defining the length of an array is in C (other than that, the first is a pointer the second is not).

I'd also like to know which one is safer.

  1. char* String = (char*) malloc(25);
  2. char String[25];

The main difference between the two array objects is the lifetime. The first one the lifetime of the object starts at malloc return and ends when free is called. The second has a lifetime which depends on the scope where it is declared. At block scope, the object is created when the block is entered until the } . At file scope, the lifetime starts with the program and ends when the program ends.

The other difference is String in the first case is a pointer and in the second case is an array name. For example, sizeof String in the first case yields the size of the pointer object but yields the size of the array object in the second case.

As a final note, do not cast the return value of malloc .

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