Sorry to bother y'all with ANOTHER basic C question, but....

Started by
5 comments, last by MainForze 21 years, 5 months ago
... What''s wrong with this code? It compiles without any errors or warnings, but it crashes horribly....

#include <stdio.h>

int main()
{
	char szServer[257];
	unsigned int wPort;

	printf("Server: ");
	scanf("%s", szServer);
	printf("Port: ");
	scanf("%u", wPort);  // <-- This is where it crashes...
        printf("Connecting to host %s on port %u...\n", szServer, wPort);

	return 0;
}
 
My guess is that it has something to do with the fact that ints are 32 bits in win32 and scanf expects 16 bits, but I''m not sure. Can somebody explain why this crashes?
"It's strange, isn't it? You stand in the middle of a library and go 'AAAAAAAGGHHHH' and everyone just stares at you. But you do the same thing on an airplane, and everyone joins in!"
Advertisement
You need to pass the address of ''wPort'', not its value. Change scanf("%u", wPort); to scanf("%u", &wPort);.

I''m almost positive that this:

quote:Original post by MainForze
scanf("%u", wPort);


should be:

 scanf("%u", &wPort);  


I haven''t worked with this sort of code in a while, but I don''t think that wPort''s undefined value would mean a whole lot to scanf

______________________________________________________________________________________The Phoenix shall arise from the ashes... ThunderHawk -- ¦þ"So. Any n00bs need some pointers? I have a std::vector<n00b*> right here..." - ZahlmanMySite | Forum FAQ | File Formats______________________________________________________________________________________
YEP! You guys were right!! At first I thought you needed to pass the variable itself instead of its address, because the scanf that filled a char buffer worked OK, but after reading your posts I realized/remembered that an array IS in fact a pointer!!
Thanks for the help guys!!

Greetz, MainForze

[edited by - MainForze on November 10, 2002 1:03:13 AM]
"It's strange, isn't it? You stand in the middle of a library and go 'AAAAAAAGGHHHH' and everyone just stares at you. But you do the same thing on an airplane, and everyone joins in!"
quote:Original post by MainForze
...At first I thought you needed to pass the variable itself instead of its address, because the scanf that filled a char buffer worked OK...


It worked because the ''char buffer'' is actually a pointer (an array).

The code should at least have given you a warning about using an non-initilized value on that line.
Yes it did initially. After getting that warning I initialized wPort to 0 and ofcourse it went away. I forgot to mention this in my first post in this thread because I thought it wouldn''t be important... bad move. ;-)
"It's strange, isn't it? You stand in the middle of a library and go 'AAAAAAAGGHHHH' and everyone just stares at you. But you do the same thing on an airplane, and everyone joins in!"

This topic is closed to new replies.

Advertisement