+ 15

problem with displaying pointer address in gcc

I have the following C program from page 31 in the MagPi-Magazine ( https://magpi.raspberrypi.org/books/essentials-c-v1/pdf ): https://code.sololearn.com/cA21a17A0a72/?ref=app If I want to compile it on Ubuntu 20.04 with the command gcc -o pointer pointer.c then I get errors and it refuses to compile. If I do the same on Raspberry Pi, it compiles smoothly without errors. And astonishing is that it also runs in sololearn code playground and shows a reasonable output but this is followed by some warnings. I also discovered with gcc -v that Ubuntu (Ubuntu 9.3.0-17ubuntu1~20.04) on my notebook uses gcc in the version 9.3.0 while Raspbian (Raspbian 8.3.0-6+rpi1) uses the version 8.3.0. My questions are: Is the given example in principle wrong? Do I have to use some extra options, and if that is the case, which should I give in the gcc-command in order to run the code also on Ubuntu?

2nd Jan 2021, 8:18 AM
Jan Markus
4 Réponses
+ 9
Problem 1: your main() function has return type `void` when it should be `int` Problem 2: %d is used for `int` types while you are trying to print `int *` type with it. Use %p instead, which is used for printing pointers https://code.sololearn.com/cZoiEcWf9l97/?ref=app
2nd Jan 2021, 8:42 AM
XXX
XXX - avatar
+ 8
For void main you will get warning. For printing variable in pointer you have to use *ptr for getting the value of pointer. For printing address you should use %p not %d.There is difference of printing value of pointer with %p and %d.%d takes 16 bits and displays it as a signed value 123 %p takes a pointer and display it in address format 0fef:0004: https://code.sololearn.com/cA205A13A6A5 You might have a look at this question: https://stackoverflow.com/questions/26155161/difference-between-d-and-p-printf-format-string-directives-in-c-language
2nd Jan 2021, 9:11 AM
The future is now thanks to science
The future is now thanks to science - avatar
+ 6
What errors are you getting? The compiler is right in showing a warning because `main` is not `int`. `void main` is not standard C, however the C standard does allow compiler implementations to accept other signatures if they wish. printf showing warnings is also fine. It is some black magic as to how printf knows that you pass in an int* rather than an int but anyway we should be happy that we are told so, as it's usually not what we want to do. The correct way would be to cast the pointer to an `intptr_t` type first, before passing that to printf, or use "%p". I suspect that raspi gcc has some default flags set, to be more lenient. (maybe -w?)
2nd Jan 2021, 8:44 AM
Schindlabua
Schindlabua - avatar
4th Jan 2021, 6:22 AM
Sonic
Sonic - avatar