Public Group

Archived

This topic is now archived and is closed to further replies.

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

This topic is 5669 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

... 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?

Share on other sites
You need to pass the address of ''wPort'', not its value. Change scanf("%u", wPort); to scanf("%u", &wPort);.

Share on other sites
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

Share on other sites
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]

Share on other sites
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).

Share on other sites
The code should at least have given you a warning about using an non-initilized value on that line.

Share on other sites
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. ;-)

• 10
• 16
• 14
• 18
• 15