字符串中的 C 字符串指针如何以空值终止?
How a C string pointer within a string is null-terminated?
假设我有一个带有参数值对的 C 字符串 ch
:
#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)=='[=10=]')); // gives 1
我的理解是p
指向ch
中的"sex=M age=30",和ch
使用相同的空终止符。 v
指向p
中的"male",我的问题是v
的空终止符存储在哪里?在p
和ch
中都是"male"之后的space,这里v
是指针,不是缓冲区。
my question is where the null terminator for v is stored?
没有。您正在调用 undefined behaviour 因为 v
未初始化。不仅是空终止符,而且 sscanf() 将 "male" 写入 v
指向的位置也是无效的。因为 v
没有指向有效的内存位置。
sscanf()
会执行空终止,但您必须传递一个有效的指针(例如 char v[5]
)。请注意 sscanf()
根本不会修改其第一个参数。所以 ch
不会被 sscanf()
修改。
假设我有一个带有参数值对的 C 字符串 ch
:
#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)=='[=10=]')); // gives 1
我的理解是p
指向ch
中的"sex=M age=30",和ch
使用相同的空终止符。 v
指向p
中的"male",我的问题是v
的空终止符存储在哪里?在p
和ch
中都是"male"之后的space,这里v
是指针,不是缓冲区。
my question is where the null terminator for v is stored?
没有。您正在调用 undefined behaviour 因为 v
未初始化。不仅是空终止符,而且 sscanf() 将 "male" 写入 v
指向的位置也是无效的。因为 v
没有指向有效的内存位置。
sscanf()
会执行空终止,但您必须传递一个有效的指针(例如 char v[5]
)。请注意 sscanf()
根本不会修改其第一个参数。所以 ch
不会被 sscanf()
修改。