【发布时间】:2021-11-19 04:48:52
【问题描述】:
我正在使用 sscanf 读取用户输入并保存到多个输出。据我了解,如果我有 sscanf(iput, %s %s %s %s, arr[0], arr[1], arr[2], arr[3]) 我最多可以有 4 个项目输入,但不需要 4;这意味着我可以只放两个,而 arr[2] ad arr[3] 将没有任何价值。但是,我认为我不理解某些东西,因为后来当我检查 arr[2]/arr[3] 的值时,它们不为空,当时我认为字符串只是用 \0 初始化的。请看一下我的代码,告诉我我猜 if 语句应该检查什么。
printf("Enter a command: ");
char input[20];
char line[5][20];
fgets(input, 20, stdin);
sscanf(input, "%s %s %s %s %s", line[0], line[1], line[2], line[3], line[4]);
....
else {
int status;
if(line[4] != NULL) {
char *args[6];
args[0] = line[0];
args[1] = line[1];
args[2] = line[2];
args[3] = line[3];
args[4] = line[4];
args[5] = NULL;
if ( fork() == 0 ) {
execv( args[0], args ); // child: call execv with the path and the args
}
else {
wait( &status );
}
【问题讨论】:
-
请发帖minimal reproducible example。由于潜在的缓冲区溢出,scanf 的使用不安全。请改用
fgets()。 -
另外,我认为您的代码甚至无法编译。 scanf("%s ..." 需要一个 char * 但你传递给它一个 char (
line[0])。 -
如果你只在格式字符串中传递了两个百分号,那么 scanf 认为你只传递了两个变量。如果它不知道最后两个它不会用任何东西填充它们 - 甚至不是 NULL。但这还不是全部:如果您声明
char line[5][20];,那么 line[x] 将始终有一个值并且永远不会为 NULL,因为您实际上已经分配了该内存。如果您希望其中一些为 NULL,则需要将其声明为char *line[5] = {0};,然后为您希望为非 NULL 的所有指针分配内存。 -
if(line[4] != NULL)这不可能是真的。line[4]是一个永远不会衰减为NULL指针的数组。