Pointer Newbie Question

Hello Community,

i am a new member. Sry for my bad grammer.

Here is my question:
Why do i get a error message from eclipse when i type in
1
2
  int *pointer;
  *pointer = &x;
?
The message is "invalid conversion from int* to int".
I think i understand the message. But when i try it on this way
 
  int *pointer = &x;
i get no error message.
Why? For me it looks like the same.
Or ist this "int *pointer = &x;" equal to "int *pointer; pointer = &x"?
Thanks for helping!

regards habakuk
Both of these examples will use the forward declaration
 
int * pointer;


You can do
 
pointer=&x;


This will assign the pointer to point at the x memory address

you can also do
 
*pointer=x;

This is dereferencing the pointer and placing the value of x into the value being held by what the pointer is pointing to.
Last edited on
1
2
 int *pointer;
 pointer = &x;


or

 
 int *pointer = &x;


You get an error because you try to assign the address to the object that your pointer points to (by dereferencing it).

EDIT:

Pindrought beat me to it :)

Last edited on
But why can i do this int *pointer = &x;?
Is this not the same like "You get an error because you try to assign the address to the object that your pointer points to (by dereferencing it)."?
Nah, you just need to think about it this way:
int* pointer = &x; // Means the same as int *pointer = &x;
Here, you can see that pointer is a pointer to an int variable and we're initializing that pointer to point to the address of x.
The * has 2 meanings, in a declaration it is a pointer type:

int* p; // p is a pointer to int

I put the * next to the type, this might be less confusing.

It is also used to dereference a pointer variable (retrieve the value that the pointer points to):

int a = *p; // a is now the same as the value that pointer p points to

To do things in order:

1
2
3
4
5
int a = 5;

int* p = &a; // pointer p points to the  address of a

int b = *p; // b is now 5 



Hope that Helps :+)

THX for all Input!
Before i ask again, I will try to understand.
Ok. I hope i got it:

1
2
3
int x = 0;
int* pointer;
pointer = &x;


same meaning to

 
int* pointer = &x;


The * in the second example is for declaration. The value assignment didnt recognize the star.
Last edited on
Topic archived. No new replies allowed.