This is a newbie C++ pointer question. I have no clue on why this happen…
I found that if i write this code. It is totally valid.
Code1
int *j; //create an pointer j
*j = 50; //assign 50 to the *j, meaning value pointed by address 50 is xxx
However, when I wanna try to make it more simple. The compiler give me this error message.
Code2
int *j = 50; //i guess this should be the same with Code1...
Compile error
error: invalid conversion from ‘int*’ to ‘int’
So why would be like that?
There’s a bit of ambiguity in the C syntax there.
is equivalent to
Actually, what you’re doing in the first snippet of code is dangerous because you haven’t allocated any memory for j before assigning a value to it yet. You’ll need to make memory for it like so:
in C:
in C++
Or point the pointer at some other block of memory that’s already valid:
Edit: It’s worth pointing out that the ambiguity has to do with the ‘*’ symbol. In the declaration,
int *j;the *j means “a pointer named j”. But when you’re using it in the second line “*j = 50”, * becomes the dereference symbol that means “the value at address j”.