2

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!

6
  • 1
    One error it should give is the void main. Commented Mar 21, 2013 at 4:50
  • x and y are both variables of type pointer to int. The reason for the first error is that istream has no overloaded extraction operator for reading a pointer (see cplusplus.com/reference/istream/istream/operator%3E%3E), and the reason for the second error is that you are attempting to dereference something not of pointer type (x[0] has type int). Commented Mar 21, 2013 at 4:57
  • @warrenm i thought i created array of pointers that are pointing to int and not array of int. what can i do to create array of pointers? Commented Mar 21, 2013 at 5:03
  • @Smatik, I'm just saying it should. Any return type other than int is deemed undefined behaviour by the C++ standard. Commented Mar 21, 2013 at 5:04
  • @chris void main is not giving any error. Why should it give? i have not specified any return. Commented Mar 21, 2013 at 5:05

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

1

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.

1 Comment

An array is not a pointer, though it can be implicitly converted to one.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.