我有一个函数,它将 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])
返回机器上指针的大小,为 8 个字节,因为它的类型为 char *
; sizeof("foo")
返回字符串“foo”加上空终止符的长度,即四个字节。
关于c - 类似的 C 字符串具有不同的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44423257/