• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 265
  • Last Modified:

Difference betweeen char[] and char* = new char[]

Hi,
I come from java background so this is confusing for me. When allocating dynamic memory in cplusplus what is the difference between allocating memory for char array using char var[40] and char* var = new char[40]?

How do I delete/free the allocated memory of char arrays in both forms?

thanks in advance.
 
0
zoollu
Asked:
zoollu
  • 2
  • 2
1 Solution
 
Infinity08Commented:
>> char var[40]

The memory is statically allocated (usually on the stack). Room for 40 characters is reserved. The size of the buffer is fixed at compile time, and cannot be modified at run time.

The memory is free'd as soon as the buffer goes out of scope (at the closing } for the block it was defined in).


>> char* var = new char[40]

The memory is dynamically allocated (usually on the heap). Room for 40 characters is reserved. The size of the buffer can be decided at run time.

The memory has to be explicitly deleted by the programmer using delete [] :

       delete [] var;

This is done as soon as you don't need the memory block any more.
0
 
zoolluAuthor Commented:
So can i allocate memory like

char var[sizeof(newitem)+30] and not care about deleting it since its gone when out of scope?
0
 
Infinity08Commented:
>> char var[sizeof(newitem)+30]

That's ok.

>> and not care about deleting it since its gone when out of scope?

Exactly.


But you won't be able to change the size of the buffer at run time. It's fixed at compile time to sizeof(newitem)+30 chars.
0
 
zoolluAuthor Commented:
thanks
0

Featured Post

[Webinar] Cloud and Mobile-First Strategy

Maybe you’ve fully adopted the cloud since the beginning. Or maybe you started with on-prem resources but are pursuing a “cloud and mobile first” strategy. Getting to that end state has its challenges. Discover how to build out a 100% cloud and mobile IT strategy in this webinar.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now