-4

New & Delete Operators

In the Visual Studio Code editor, I tried to use the new and delete operators, but the editor throws an error which I am unable to figure out. I tried out everything to remove the error, but all in vain!!!

#include <iostream>
using namespace std;

int main()
{
    int avg, *ptr1, *ptr2, *ptr3;

    ptr1 = new int;
    ptr2 = new int;
    ptr3 = new int;


    cout << "Enter the first number : ";
    
    cin >> *ptr1;
    
    cout << "Enter the second number : ";
    
    cin >> *ptr2;
    
    cout << "Enter the third number : ";
    cin >> *ptr3;
    
    avg = (*ptr1+*ptr2+*ptr3)/3;
    cout << "Average is : " << avg << endl;

    delete ptr1;
    delete ptr2;
    delete ptr3;

    return 0;
}

This is the Error that is displayed:

image

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • 2
    Rename your file to not contain `&`. It's generally a good idea to not have any funny characters in filenames (including spaces). – HolyBlackCat Jan 20 '22 at 18:33
  • I suspect the name of your source file contains one-or-more ill-advised characters. – Eljay Jan 20 '22 at 18:34
  • 1
    Is this a [mre]? From your error, I suspect `int main(){}` would produce the same results. How did you determine that `new` and `delete` are causing this error? – Drew Dormann Jan 20 '22 at 18:37
  • 1
    The powershell output seems pretty clear and it points at the ampersand. This has nothing to do with `new` and `delete`. – Ted Lyngmo Jan 20 '22 at 18:41
  • 3
    Summary: This has nothing to do with new and delete or even the C++code. The shell used to build the program could not consume the filename **n&d.cpp** because of the **&** in it. Change the name to **n_and_d.cpp** or something that avoids using characters commonly used in programming as operators or delimiters. – user4581301 Jan 20 '22 at 18:48
  • Side note: I guess this is just an exercise, but in real life, it makes no sense to `new` a single native type like `int`. Just use a plain `int` instead. – prapin Jan 20 '22 at 19:19

1 Answers1

0

The error message has been misinterpreted by the asker and has nothing to do the asker's use of with new and delete or any of the asker's C++ code (which could use some error checking on the IO but otherwise seems correct). Visual Studio Code couldn't start compiling the code because the shell used to build the program could not consume the filename n&d.cpp because of the & in it.

Change the name to n_and_d.cpp or any other name that avoids using characters commonly used in programming as operators or delimiters. There will be similar problems in other build systems because of the spaces in the path leading to the source file.

user4581301
  • 33,082
  • 7
  • 33
  • 54