简体   繁体   中英

Scanf doesn't work well with while loop

So I have the following code:

void main(int argc, char **argv)
{
    int loggedIn=0;
    char *currentCommand;

    while (!loggedIn)
    {
    printf("Enter your command:");
    scanf("%s",currentCommand);
    printf("\n%s\n",currentCommand);
    }
}

The problem is scanf() works well the first time, then is starts reading (null) and the output would be Enter your command: (null) in an infinite loop.

I want to input more commands and stop when I change the value of loggedIn, but once I input one command, it starts printing Enter your command: (null) endlesly.

您需要使用malloc将内存分配给currentCommand指针(并在末尾释放它)或在开始时为其分配大小,例如

char currentCommand[256];

currentCommand is pointer variable who will save address(which is integer) of char type variable and have a size of 4 bytes (32 bit machine).

Now when you write ℅s in scanf you are supposed to pass address of char array.(which you haven't declared), so scanf will take the address (value saved in currentCommand which is garbage).

The most important thing while using character pointers is you can create a character array at the time of declaration ie,

char *p="Hello World";

This creates memory in data/code section which is read only section.

And you cannot create a character array with scanf() function. Should have to use dynamic memory allocation or initialize as above

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