c - Sscanf 在提取字符串时未按预期运行

标签 c scanf

我有一个 SPARQL 查询,例如“select ?Y ?Z where ...”。我想要做的就是提取变量“?Y”和“?Z”。我写了以下循环:

char *p = "select ?Y ?Z where condition";
char *array[2];

p += strlen("select");        /* advancing the pointer */

for(int i = 0; i < 2; i++)
{
        sscanf(p, "%m[?a-zA-Z] %[^\n]", array[i], p);    /* 'm' tells sscanf to perform dynamic memory allocation */
        printf("%s, ", array[i]);
        printf("%s, ", p);
}

但是,我没有得到预期的行为。 array[1] 包含垃圾,array[2] 包含 null。

最佳答案

基于 http://man7.org/linux/man-pages/man3/scanf.3.html
例如有

char *p;
n = scanf("%m[a-z]", &p);

我认为你应该改变你的

sscanf(p, "%m[?a-zA-Z] %[^\n]", array[i], p);

sscanf(p, "%m[?a-zA-Z] %[^\n]", &array[i], p);

看看 %m 如何与 char ** 配对,而不是与 char* 配对。

我建议阅读 THIS讨论也是如此。

我还注意到你的 pchar * 并且你用字符串常量初始化它,然后尝试调用 sscanf 覆盖它。

除此之外,您还可以在同一个函数调用中读取和写入 p 指向的内存。我在这里不是 100% 确定,但这可能是未定义的行为。

希望对您有所帮助。

关于c - Sscanf 在提取字符串时未按预期运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19895784/

相关文章:

c++ - 32位小数浮点/ double 解析

c++ - Cuda 分配和返回数组从 gpu 到 cpu

c - header 的宏定义,放在哪里?

c - fscanf 不读取/识别 float ?

c - scanf() 和 printf() 中的字符串变量名之前的 & 符号或没有 & 符号?

c - 使用 scanf 读取 C 中一定数量的字符?

clockid_t(clock_gettime 第一个参数)可移植性

C fscanf 返回 null

c++ - 一个接受输入小写字母的短程序,它给出大写字母并在按下回车键时退出

Java native 接口(interface) : Object Passing