简体   繁体   中英

C++ difference between “char *” and “char * = new char[]”

So, if I want to declare an array of characters I can go this way

char a[2];
char * a ;
char * a = new char[2];

Ignoring the first declaration, the other two use pointers. As far as I know the third declaration is stored in heap and is freed using the delete operator . does the second declaration also hold the array in heap ? Does it mean that if something is stored in heap and not freed can be used anywhere in a file like a variable with file linkage ? I tried both third and second declaration in one function and then using the variable in another but it didn't work, why ? Are there any other differences between the second and third declarations ?

  • In the first case, a[2] stores 2 chars on the stack.
  • In the second case, there is no allocation at all - a is an uninitialized pointer.
  • In the third case, 2 chars are allocated on the heap.

You are right in thinking that heap allocated variables can be shared across your process, however, you will need to ensure that you pass the location of the allocated heap memory around - you do this eg by returning a from your method or function, or by increasing the scope of a eg to class scope.

delete will free heap allocations. In your case, delete should only be used in scenario 3, since in #1, stack variables are cleaned up when they go out of scope, and in #2, you haven't allocated any memory.

Because the above can easily lead to chaos during the transfer of ownership over the heap allocations, smart pointers such as auto_ptr or boost's shared_ptr can be used to make life simpler.

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