sscanf的奇怪行为,用绳子 [英] Strange behaviour of sscanf with string
问题描述
我已经得到了与的sscanf
麻烦。要检查它,我做了一个简单的文件,所以当我编译如下:
I've got a trouble with sscanf
. To check it I made a simple file, so when I compile this:
#include <stdio.h>
main(){
char *a;
/* */
char *s = "GET /something HTTP/1.1\r\n";
printf("sscanf: %d\n", sscanf(s, "GET %s HTTP", a));
printf("a: %s\n", a);
/* */
printf("sscan: %d\n", sscanf("GET /more HTTP/1.1\r\n", "GET %s HTTP", a));
printf("a: %s\n", a);
}
我得到正确的输出:
I get right output:
sscanf: 1
a: /something
sscan: 1
a: /more
但是,当我空注释之间注释行唱歌,我得到:
But when I comment lines between empty comments sings, I get:
sscan: 0
a: (null)
问题1 :这怎么能这么
和多一点:如果我写的char *一个= NULL
,我得到:
And a little more: if I write char *a = NULL
, I get:
sscanf: 0
a: (null)
sscan: 0
a: (null)
问题2 :为什么?
推荐答案
您正在复制一个字符串的指针未初始化( A
)。你需要分配给它的存储(以的malloc
),或声明数组。
You're copying a string to an uninitialised pointer (a
). You need to allocate storage for it (with malloc
), or declare an array.
实现有时会出现正常工作时,你不分配任何存储。当您指定为NULL A
,的sscanf
不存储任何东西,所以你尝试打印一个串用一个NULL指针(其中的printf
打印为(空)
)。在某些系统上,你的程序只会崩溃。
Implementations can sometimes appear to work correctly when you don't allocate any storage. When you assign NULL to a
, sscanf
fails to store anything, and so you try to print a "string" with a NULL pointer (which printf
prints as (null)
). On some systems, your program would simply crash.
有一个编译器/库扩展,它允许字符串自动分配,但显然这不是便携,并不是所有的编译器都支持它。
There is a compiler/library extension that allows automatic allocation of strings, but obviously this is not portable and not all compilers support it.
char *a;
scanf("%ms", &a;) // allocates storage for a
您可以将未初始化的指针传递给函数,但要注意的&放大器;
You can pass an uninitialised pointer to the function, but note the &
.
这篇关于sscanf的奇怪行为,用绳子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!