-2

I have searched the web and found nothing regarding this..

char array[50];
char *array = new char[50];

Tell me the difference between them..

4
  • Have you tried to google for stack vs heap allocations like that: geeksforgeeks.org/stack-vs-heap-memory-allocation Commented Apr 3, 2021 at 7:37
  • Only one of them can (and should) be passed to the delete[] operator... Also sizeof yields different results... Commented Apr 3, 2021 at 7:43
  • What do you think is the similarity between them? In programming, "what's the difference between" type questions generally don't get you very far. You should rather ask something directly useful, such as "when would I do things this way and when would I do things the other way?" - except that this is opinion-based and thus off topic for Stack Overflow. More generally, to teach yourself at this level, you want a discussion forum such as reddit.com/r/learnprogramming, or somewhere on Quora; not Stack Overflow. Commented Apr 3, 2021 at 8:00
  • std::vector should be used to replace both... (or std::array) Commented Apr 3, 2021 at 8:18

2 Answers 2

2
  1. char array[50] is 50*sizeOfChar space allocated on stack. char *array = new char[50] is 50 * sizeOfChar space allocated on heap, and address of first char is returned.
  2. Memory allocated on stack gets free automatically when scope of variables ends. Memory allocated using new operator will not free automatically, delete will be needed to be called by developer.
Sign up to request clarification or add additional context in comments.

Comments

0

Mixing C/C++ is a nice though sometimes confusing:

char array[50];

Allocation on stack, so you don't need to worry about memory management. Of course you can use std::array<char, 50> array which being C++ brings some advantages (like a method which returns its size). The array exists until you leave its scope.

char *array = new char[50];

Here you need to manage the memory, because it is kept in the heap until you free it. Important, you should use this whenever you want to remove it:

delete [] array;

There also exist free(array) (Standard C) and delete (without parenthesis). Never use those, whenever you use new someType[...].

Other that in both you still have a char array of 50 elements you can play with :-)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.