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

fabian
  • 80,457
  • 12
  • 86
  • 114
Diken Mhrz
  • 327
  • 2
  • 14
  • Have you tried to google for stack vs heap allocations like that: https://www.geeksforgeeks.org/stack-vs-heap-memory-allocation/ – Ilian Zapryanov Apr 03 '21 at 07:37
  • Only one of them can (and should) be passed to the `delete[]` operator... Also `sizeof` yields different results... – fabian Apr 03 '21 at 07: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 https://reddit.com/r/learnprogramming, or somewhere on Quora; not Stack Overflow. – Karl Knechtel Apr 03 '21 at 08:00
  • [std::vector](https://en.cppreference.com/w/cpp/container/vector) should be used to replace both... (or [std::array](https://en.cppreference.com/w/cpp/container/array)) – David C. Rankin Apr 03 '21 at 08:18

2 Answers2

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.
Rana Vivek
  • 126
  • 2
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 :-)

Gerhard Stein
  • 1,543
  • 13
  • 25