Search code examples
c++charintoperator-overloadingnew-operator

C++ dynamic memory allocation (char[] and int[])


str is a pointer, why not use str for input and output? Not *str.
p is a pointer, why use *p for input and output? Not p.

#include<iostream>
using namespace std;

int main()
{
   
    char* str = new char[20];
    cin>>str;
    cout<<str<<endl;
    delete []str;

    int* p = new int[3];
    cin>>*p;
    cout<<*p<<endl;
    delete []p;

    return 0;
}

Solution

  • The operator overloads << and >> have special overloads for const char* and char* respectively, because those are null-terminated C-style strings. They are treated diifferently than other pointers/other arrays.

    Here's a little comparison of the semantics used:

    cin >> str;
    

    means "read a null terminated string into an array, where str is the pointer to the first element".

    cout << str; 
    

    means "Print a null terminated string, where str is the pointer to the first element".


    However there are such semantics for other pointer types like int*.

    cin >> p;
    

    wont work, there is no such thing as "reading an array of ints", or "reading a pointer", while

    cin >> *p; 
    

    works and means "read a single integer and store it in the value of p", that is, the first element in the array get's modified.

    cout << p;
    

    means "print the value of the pointer", again, because there are no special semantics for int* like "Print array of ints". On the other hand

    cout << *p;
    

    meanse "Print one integer, that is the value of p", that is, the first element in the array get's printed.