Kevin
Kevin

Reputation: 43

Would there be any possible issues with declaring a pointer value in separate lines in C++, instead of using the 'new' function?

I'm new to C++ and currently having a hard time with pointers.

I was wondering if there is a preferred method of coding between the two methods shown below:

#include <iostream>

using namespace std;

int main(){
    // method 1
    int* n;
    *n = 2;
    cout << "address of n in main(): " << n << "\n"; //returns 0
    cout << "value inside of n in main(): " << *n << "\n"; // returns 2

    // method 2
    int* m = new int(2);
    cout << "address of m in main(): " << m << "\n"; //returns some address
    cout << "value insdie of m in main(): " << *m << "\n"; // returns 2
}

The first method returns the following:

address of n in main(): 0
value inside of n in main(): 2

The Second method returns the following:

address of m in main(): 0x6c2cc0
value inside of m in main(): 2

Q1. What would be possible issues with having the address of n in main():0? (it only behaves like this on an online compiler sorry. Nevermind this question.)

Q2. What is the "new" declaration method called?

Upvotes: 0

Views: 51

Answers (1)

Acorn
Acorn

Reputation: 26176

What would be possible issues with having the "address of n in main():0"?

If you are lucky, crashing the program due to segfault. If you are not, memory corruption, undefined behavior, etc.

The reason is that you are using an effectively random memory address that has not been mapped/reserved/allocated to your process.

What is the "new" declaration method called?

There is no "name" for the "method". new is a keyword and an operator, too. It is the standard way of allocating memory in C++. Although, in almost all cases, you will use a container instead that manages the memory for you, like std::vector or std::unique_ptr.

Upvotes: 1

Related Questions