c - 类似的 C 字符串具有不同的大小

标签 c string pointers types sizeof

我有一个函数,它将 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/

相关文章:

c - D3D11CreateDeviceAndSwapChain 软件参数

c - 为什么在 for 循环中包含 for 循环

python - 将python中的字符串从左边开始分成两部分

c++ - 不正确的字符串比较

c - C 中 fwrite 和 struct 的奇怪错误

c - 如何将一个简单的客户端服务器 TCP 程序转换为非阻塞程序

c - 从图书馆给出指针

java - 计算逆波兰表示法中算术表达式的值

c++ - C++中删除指针对象

使用指针算术将数组元素更改为用户输入