比方说,我有一个C字符串ch
与参数值对:字符串中的C字符串指针如何以空字符结尾?
#include <string.h>
char ch[] = "name=John sex=male age=30"; // null-terminated C string
char *p, *v; // pointers to parameter and value
p = strstr(ch, "sex="); // p now points to "sex=male age=30"
sscanf(p, "sex=%s", v); // get the value for sex
printf("sex = %s\n", v); // gives "male", works as expected
printf("length of v is %i\n", strlen(v)); // gives 4
printf("is v null-terminated? %i\n", (*(v+4)=='\0')); // gives 1
我的理解是,p
分“性别= M年龄= 30” ch
,并使用相同的空终止为ch
。 v
指向p
和中的“男性”我的问题是v
的空终止符存储在?这是p
和ch
中的“男性”之后的空格,这里的v
是指针,而不是缓冲区。
我现在明白我应该做一些类似'char v [5]'而不是'char * v'的东西。在'sscanf'后面打印'ch'时崩溃。没有打印,它为我想:) –