Dynamic memory allocation of array in C & C++

The difference exists due to the existence of references in C++.
In C++ operator >> for objects of type int is declared the following way

basic_istream<charT,traits>& operator>>(int& n);

As you see the parameter of the operator has type int &. It means that the argument is passed to the function by reference that is the function deals directly with the argument not with its copy.

So this statement

cin>>*(p+i);

is equivalent to

cin.operator( *( p + i ) );

and the compiler does not creates a copy of the object specified by the expression *( p + i ). It uses the object itself because the object is passed by reference.

In C in fact there is also used a reference to the argument but it is specified as a pointer because the notion of references is not defined in C.

When somebody says that an object is passed by reference to a function in C it means that the object is passed indirectly using a pointer to the object.
In C++ it means that there is used the notion of the reference.

So if you want that function scanf would store the input data in the object itself you have to pass it indirectly to the function by using a pointer to the object.

scanf("%d",(p+i));

Here p + i is a pointer to object *( p + i ).

Consider these two simple programs

C++

#include <iostream>

int main()
{
    int x = 10;
    int &rx = x;

    std::cout << "x = " << std::endl;

    rx = 20;

    std::cout << "x = " << std::endl;
}

The same in C can be written the following way using a pointer because C does not have the notion of references

C

#include <stdio.h>

int main( void )
{
    int x = 10;
    int *rx = &x;

    printf( "x = %d\n", x );

    *rx = 20;

    printf( "x = %d\n", x );
}

Leave a Comment