-5

I just want to know what's the difference between like:

Student std[2];

and

Student std* = new Student[2];

I know the 1st one is like an array and you declare and a new memory for each index, but then how is it different if you do it the other way and how different it is when accessing members in the class?

I tried finding similar questions but no luck.

Thanks in advance.

  • 1
    The first one is only allowed if `count` is a compile time constant, the second one doesn't even compile – UnholySheep May 24 '18 at 16:19
  • 1
    First one is an array (that is on stack) that contains `count` number of items type `Student` (assuming count is a constant). The second one is invalid, as new returns a pointer to an allocated array of `Student` but on the left side of an assignment is a variable type `Student`, where there should be a `pointer to Student` instead (`Student *std`). Also note that I personally wouldn't name my variables std as it is also a name of std namespace. – StereoBucket May 24 '18 at 16:22
  • 4
    It won't be helpful for you in the long run to get an answer to this specific question. I recommend working through a [good textbook](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) and getting a solid understanding of the basics of the language. – R Sahu May 24 '18 at 16:25
  • Possible duplicate of [What is difference between instantiating an object using new vs. without](https://stackoverflow.com/questions/3673998/what-is-difference-between-instantiating-an-object-using-new-vs-without) – xskxzr May 24 '18 at 16:39

1 Answers1

0

Student std[count]; is allocated on the stack and needs to have a predetermined(constant) size. count needs to be a compile time constant.

Student std = new Student[count]; will give you errors. The "new" operator allocates memory on the heap and returns a pointer to the newly allocated memory. This allows you to dynamically allocate memory without a predetermined size at compile time. You should write Student* std = new Student[count]; This will give you a pointer to the first element of the array that was created. Also, you will need to deallocate the memory once you are done with delete[] str;. If you don't, you will have a memory leak.

  • The usual pedantic warning: You may go through your entire career and never see one, but it is possible for a C++ implementation to not use stacks and heaps. – user4581301 May 24 '18 at 17:08
  • @user4581301 • I've seen one! Embedded system, as an IBM mainframe console-to-serial-data converter. The firmware was written in C++, and all the memory was carved out of the available memory using static variables either global scope or function scope. (No exceptions, no RTTI, no dynamic_cast, no heap, no stack for variables... lots of stock C++ features were not allowed.) – Eljay May 24 '18 at 17:27