简体   繁体   中英

Simple C code keeps crashing

So this is the code i did:

#include <stdio.h>
#include <stdlib.h>

int main()
{
char playerName;
int playerAge;

printf("What's your name, and your age?\nYour name: ");
scanf("%s\n", playerName);
printf("Your age: ");
scanf("%d\n", &playerAge);
printf("Okay %s, you are %d years old!", playerName, playerAge);

return 0;
}

And everytime i run it, after i input my name it crashes and i don't know how to fix it. These 3 things appear when it closes:

format '%s' expects argument of type 'char *', but argument 2 has type 'int' [-Wformat]|

format '%s' expects argument of type 'char *', but argument 2 has type 'int' [-Wformat]|

'playerName' is used uninitialized in this function [-Wuninitialized]|

What is my mistake?

scanf("%s\\n", playerName); is wrong because %s call for char* data but playerName here is type char .

You have to make playerName an array of characters and set max length of input to avoid buffer overflow.

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    char playerName[1024];
    int playerAge;

    printf("What's your name, and your age?\nYour name: ");
    scanf("%1023s\n", playerName); /* max length = # of elements - 1 for terminating null character */
    printf("Your age: ");
    scanf("%d\n", &playerAge);
    printf("Okay %s, you are %d years old!", playerName, playerAge);

    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM