Smatik
Smatik

Reputation: 407

difference between a pointer and a pointer array

I made a code

#include <iostream>
#include<conio.h>
using namespace std;

void main()
{
    int *x,*y;
    x=new int[1];
    y=new int;
    cin>>y;   //Gives error probably because y is a pointer and not a variable
    cin>>*y                 //works fine
    cin>>x[0]>>x[1];
    cout<<x[0]<<x[1];
    cout<<*x[0];         //gives error
    cout<<y;
    cout<<*y;

    getch();

}

gives error.why?I remember i declared x as a pointer array and now i m doing the same i did with *y.Does it mean that a pointer array becomes a variable?plz help!

Upvotes: 2

Views: 171

Answers (3)

Serdalis
Serdalis

Reputation: 10489

What you are actually doing with that line of code is similar to:

cout<<**x;

Because using x[0] will dereference the 0th element of x.

As you can see by your definition of x, x is just a pointer, not a pointer to a pointer, so dereferencing it twice will not work since you are trying to dereference a variable.

What the line:

x=new int[1];

is actually doing is just saying "assign an array of ints, size 1 to this pointer", which will just make x point to a block of memory big enough to store 1 int.

Upvotes: 1

SeasonalShot
SeasonalShot

Reputation: 2569

The meaning of the array:

x[0]

is equivalent to *(x+0);

As you know array is array is nothing but pointer in its root.

So any array that has x[a] or x[a][b] can be expanded as

*(x+a) or *(*(x+a)+b)

Based on this , i hope you found your answer.

Upvotes: 1

DavidA
DavidA

Reputation: 4184

x is a pointer to an int. You have allocated an array of ints, which is a single int long. Therefore x[0] is an int and *x is an int. However, *x[0] means you are saying that x[0] is a pointer which you are dereferencing. However, it isn't a pointer, it is an int. That is why there is an error.

Upvotes: 1

Related Questions