英文:
Why does scanf("%s", val); return null?
问题
我试图将一个字符读入名为val的char*,但当我使用scanf()时,它返回null。以下是我的代码:
#include <stdio.h>
int main(int argc, char *argv[])
{
    char *val;
    if (argc == 2)
    {
        val = argv[1];
    }
    else
    {
        scanf("%s", val);
    }
    printf("Val = %s", val);
}
如果我尝试使用malloc(),它会在输入只有一个字符长时不断从标准输入中读取,而这正是我希望我的输入的长度。
英文:
I'm trying to read a single character into a char* called val and when I use scanf() it returns null. Here is my code:
#include <stdio.h>
int main(int argc, char *argv[])
{
    char *val;
    if (argc == 2)
    {
        val = argv[1];
    }
    else
    {
        scanf("%s", val);
    }
    printf("Val = %s", val);
}
If I try to use malloc(), it will continuously read from standard input if the input is one character long, which is how long I want my input to be.
答案1
得分: 1
scanf("%s", val); 返回 null 的原因是 scanf() 需要将输入读入到一个有效的位置。
在 scanf("%s", val); 中,代码将一个未初始化的指针 val 传递给 scanf(),这会导致_未定义行为_(UB)。
相反,应该传递一个指向已准备好接受输入的内存位置的指针。
- 
传递一个指向已准备好接受字符的位置的指针。
 - 
使用一个_宽度_来避免溢出。
 - 
检查返回值。
 
    char *val;
    char s[100+1]; 
    if (argc == 2) {
      val = argv[1];
    } else {
      if (scanf("%100s", s) != 1) {
        fprintf(stderr, "无效的输入\n");
        return -1;
      }
      val = s;
    }
要读取_单个_字符,可以使用以下方式:
    char ch; 
    if (scanf("%c", &ch) != 1) {
      fprintf(stderr, "无效的输入\n");
      return -1;
    }
英文:
> Why does scanf("%s", val); return null?
scanf() needs to read input into a valid location.
With scanf("%s", val);, code passes to scanf() an uninitialized pointer val to scanf().  This leads to undefined behavior (UB).
Instead, pass a pointer to memory ready to accept the input.
- 
Pass a pointer to a location ready to accept characters.
 - 
Use a width to avoid overrun.
 - 
check the return value.
 
    char *val;
    char s[100+1]; 
    if (argc == 2) {
      val = argv[1];
    } else {
      if (scanf("%100s", s) != 1) {
        fprintf(stderr, "Invalid input\n");
        return -1;
      }
      val = s;
    }
To read a single character use:
char ch; 
if (scanf("%c", &ch) != 1) {
  fprintf(stderr, "Invalid input\n");
  return -1;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论