0

After searching through this forum and other forums relating to C++ and Dynamic Memory; I would like to know the indepth reason on why do you have to declare a dynamic memory allocation in either a Class or in a function for the program to compile?

e.g.

//place a dynamic memory allocation here and the program won't compile

int main (void)
{

int * Total_N;
Total_N = new int; //place a dynamic memory allocation here and the program compiles

}

As the book I'm learning from doesn't go into an indepth explanation, so any help would be appreciated. Thank you.

3
Contributors
3
Replies
5
Views
7 Years
Discussion Span
Last Post by sfuo
0

The error you are asking about is not just for dynamic memory it is for any time you try to assign outside of a function.

You can declare outside of functions like int *sean = new int; but sean = new int; will give you an error because you are not declaring assigning the variable and declaring at the same time.

0

This is what he was trying to do and it was giving him an error.

#include <iostream>

using namespace std;

int *sean; //declaring variable
sean = new int; //cant assign out of a function without declaring at the same time

int main()
{
	//int *sean = new int;
    return 0;
}
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.