We help IT Professionals succeed at work.

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

zoollu
zoollu asked
on
Medium Priority
277 Views
Last Modified: 2012-05-06
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.
 
Comment
Watch Question

CERTIFIED EXPERT
Top Expert 2009
Commented:
>> 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.

Not the solution you were looking for? Getting a personalized solution is easy.

Ask the Experts

Author

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?
CERTIFIED EXPERT
Top Expert 2009

Commented:
>> 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.

Author

Commented:
thanks
Access more of Experts Exchange with a free account
Thanks for using Experts Exchange.

Create a free account to continue.

Limited access with a free account allows you to:

  • View three pieces of content (articles, solutions, posts, and videos)
  • Ask the experts questions (counted toward content limit)
  • Customize your dashboard and profile

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.