简体   繁体   English

使用printf然后在循环中使用scanf

[英]using printf and then scanf in loop

char *str;
while(1)
{
    printf("$$$$>");
    scanf("%s",str);
}

In this code I just want to print a command prompt. 在此代码中,我只想打印一个命令提示符。 When user inputs something nothing happens and the command prompt is printed again. 当用户输入任何内容时,什么也没有发生,并且命令提示符再次打印。 But the scanf() runs once and then $$$$> is printed in loop. 但是scanf()运行一次,然后在循环中打印$$$$>。 The code runs when I tried to take a character array instead of str pointer. 当我尝试采用字符数组而不是str指针时,代码将运行。 why? 为什么?

char *str; char * str;

You used str without initializing it. 您使用了str而不进行初始化。 Using an uninitialized pointer in another function like scanf is a recipe for program to crash. 在诸如scanf类的另一个函数中使用未初始化的指针是程序崩溃的诀窍。

You can fix the issue by malloc (dynamically allocating) for str pointer, but for such simple usage, you can use array instead. 您可以通过为str指针使用malloc (动态分配)来解决此问题,但是对于这种简单用法,可以使用array代替。

char str[100] = "";
while(1)
{
    printf("$$$$>");
    // scanf("%s",str);  // not recommended
    fgets( str, sizeof( str ), stdin );  // fgets is better
}

如果您没有分配str可以指向的内存缓冲区,则在str declecle下添加以下行:

str=malloc(sizeof(char)*1000);

You must allocate the memory to the string after declaring the pointer. 声明指针后,必须将内存分配给字符串。 You can do it by using malloc or calloc functions. 您可以使用malloc或calloc函数来实现。

char *str = (char*) malloc(sizeof(char) * 100);

or 要么

char *str = (char*) calloc(100, sizeof(char));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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