相似的 C 字符串有不同的大小
Similar C strings have varying sizes
我有一个函数,它将 const unsigned char *
类型的参数作为其输入之一。
函数(下面提到)
someType *doSomething (someStruct *, const unsigned char *);
或 judyData *getFromJudy (judyConfig *, const unsigned char *)
.
我还有一个字符串数组,char* i[10]
。
假设,i[2] = "foo"
。现在,当我 运行
时得到不同的结果
doSomething(struct_instance, i[2])
和 doSomething(struct_instance, "foo")
.
谁能帮我看看这种情况是什么时候出现的?
有没有办法对这个指针指向的值进行类型转换,使其表现得像一个普通的字符串文字?
编辑:
共享代码示例。
函数:
// get an entry from the index, return it or null
judyData *getFromJudy (judyConfig *cnf, const unsigned char *key) {
judyData *data;
JudySlot *cell;
int current;
cell = judy_slot((Judy *) cnf->idx, (unsigned char *) key, (size_t) strlen((const char *) key));
if (cell) {
data = (judyData *) *cell;
// doesn't enter this if "foo" is not used and i[2] is used.
if (data->count == 0) {
return NULL;
}
return data;
}
return NULL;
}
和 char * i[10]
。它被称为
data = getFromJudy (obj, "foo")
sizeof(i[2])
returns 你机器上指针的大小,八个字节,因为它是 char *
类型; sizeof("foo")
returns 字符串的长度 "foo" 加上空终止符,即四个字节。
我有一个函数,它将 const unsigned char *
类型的参数作为其输入之一。
函数(下面提到)
someType *doSomething (someStruct *, const unsigned char *);
或 judyData *getFromJudy (judyConfig *, const unsigned char *)
.
我还有一个字符串数组,char* i[10]
。
假设,i[2] = "foo"
。现在,当我 运行
doSomething(struct_instance, i[2])
和 doSomething(struct_instance, "foo")
.
谁能帮我看看这种情况是什么时候出现的? 有没有办法对这个指针指向的值进行类型转换,使其表现得像一个普通的字符串文字?
编辑:
共享代码示例。
函数:
// get an entry from the index, return it or null
judyData *getFromJudy (judyConfig *cnf, const unsigned char *key) {
judyData *data;
JudySlot *cell;
int current;
cell = judy_slot((Judy *) cnf->idx, (unsigned char *) key, (size_t) strlen((const char *) key));
if (cell) {
data = (judyData *) *cell;
// doesn't enter this if "foo" is not used and i[2] is used.
if (data->count == 0) {
return NULL;
}
return data;
}
return NULL;
}
和 char * i[10]
。它被称为
data = getFromJudy (obj, "foo")
sizeof(i[2])
returns 你机器上指针的大小,八个字节,因为它是 char *
类型; sizeof("foo")
returns 字符串的长度 "foo" 加上空终止符,即四个字节。