#### Archived

This topic is now archived and is closed to further replies.

# the point in char* when theres char variable[] ?

This topic is 5841 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

what is the point in going through the hassle of...
  char *whatever; whatever = new char[size+1]; strcpy(whatever, "hello"); delete [] whatever; 
when you can use something like
  char whatever[] = "hello"; 
i dont see the point in the first code segment, if you can use the second one like shown. anyone?

##### Share on other sites
dynamic allocation vs static allocation

in the top instance the memory is allocated at runtime and can be adjusted at the that time to suit.

In the second instance the memory allocated is determined at compile time and is hence less flexible.

##### Share on other sites
Eagleboy has the words of truth.
Anyway, the "hassle" is often necessary because everyone wants to avoid nasty situations where you get an error simply because you get either a memory overflow, or then you need some important string and half of it gets cropped away.

char *whatever;
whatever = new char[size+1];
strcpy(whatever, "hello");
delete [] whatever;

The above piece of code allows you to dynamically adjust the size of the string... which is sure to happen often. If you want to use this:

char whatever[] = "hello";

Then why not write

const char whatever[] = "hello";

because it is less prone to errors. The one that you suggested being easier... well yes, but try to insert "hellototheentireworld" into the same variable My point is that you cannot resize the char variable if you don''t use pointer. If you need a static string, then it might be good to make it const to avoid errors.

- A.J. -
"Where is the KABOOM!? There was supposed to be an earth-shattering KABOOM!"

• ### Forum Statistics

• Total Topics
628642
• Total Posts
2983998

• 9
• 9
• 10
• 21
• 20