0

Why is this assignment wrong?

int main() { int var=100; int *p=&var; //such assignment works correctly int *p; p=&var; //and this too } int var=100; int *p; *p=&var; //but why is this wrong? Why can I only make both the declaration of a pointer and the assignment in the same line or p=&var in the next one? Not *p=&var?

26th May 2017, 10:57 AM
Krzysztof Szewczyk
Krzysztof Szewczyk - avatar
4 Respostas
+ 1
You look like confused between integer and pointer to integer. The two are different types. The first assignment is equivalent to the second. First is likely a syntactic sugar of the second. With the third, you are assigning pointer to integer to an integer type. &p is dereferenced before the assignment happens. The derefenced type is integer whereas &val is of type pointer to integer. The assignment makes no sense. Plus signed integer sure has a shorter range than likely unsigned integer or long that underlies the pointer to integer type.
26th May 2017, 11:16 AM
Venkatesh Pitta
Venkatesh Pitta - avatar
+ 1
@krzysztof Szewczyk true to a bit. int* p; declares a pointer to integer. whereas int* p, q; declares p as pointer to integer and q as int. This is because the grammar is specified this way. This is originally the grammar of C. This grammar I think made writing compilers easier than the one that would have meant both p and q are pointers to integer in the previous paragraph. Until GNU's g++ came along, all the professional C++ compilers were compiling C++ into C and in turn invoked the C compiler to do the rest of compilation. This meant having more of C grammar in C++ grammar made the lives of C++ compiler writers easier. So this got carried into C++. It is a colourful, entertaining history. If it interests you, I recommend reading Deep C Secrets by Peter van der Linden. Many quirks like this are explained in this book.
26th May 2017, 8:38 PM
Venkatesh Pitta
Venkatesh Pitta - avatar
0
Ok, thx a lot. I guess I understand it much better now. If I'm right it should be a little better to just make a pointer declaration this way: int* p; because this asterisk(*) is basically to define the type as pointer-to-int. Right?
26th May 2017, 12:01 PM
Krzysztof Szewczyk
Krzysztof Szewczyk - avatar
0
because you're trying to assign an address to a value, the *-operator is dereferencing the pointer
26th May 2017, 12:02 PM
‎ɐısıօլɐ
‎ɐısıօլɐ - avatar