【问题标题】:Type casting, easy question for people good at C类型转换,擅长 C 的人的简单问题
【发布时间】:2009-02-19 10:41:44
【问题描述】:

我有一个库,我必须将 (char **)&return_string 传递给函数 hci_scan 如这段摘录所示:

char return_string[250];
int num_hosts;

if ((num_hosts = hci_scan((char **) & return_string, 0x03)) > 0) {
    //case where one or more devices are found...
} else {
    //case where zero devices are found...
}

执行后,return_string 中的内容是什么? (到目前为止,我得到的只是内存地址)

感谢您的帮助

【问题讨论】:

    标签: c pointers casting


    【解决方案1】:

    hci_scan 的文档应该准确地告诉你它会产生什么,但我猜它会是一个字符串,其内存是从hci_scan 中分配的。您真的不需要将return_string 定义为数组; char *return_string; 应该也能正常工作。

    【讨论】:

      【解决方案2】:

      如果 hci_scan 修改传递给它的值,就像使用 (char**) 似乎暗示的那样,那么您的代码是非法的,因为您不允许更改大批。我怀疑 hci_scan 想要分配内存,所以你想要这样的东西:

      char * buf;
      hci_scan( & buf );   // allocates string & points buff to it
      

      但您确实需要阅读 hci_scan 文档以确保。

      【讨论】:

        【解决方案3】:

        char (*) [] 转换为char ** 是错误的。考虑以下代码:

        char foo[42];
        assert((void *)foo == (void *)&foo); // this will pass!
        

        &foochar (*) [42] 类型,并引用数组的内存位置,这与(char *)foo&foo[0] 指向的位置相同!

        这意味着

        char ** p = (char **)&foo;
        

        一样
        char ** p = (char **)foo;
        

        这通常不是程序员想要做的。

        【讨论】:

          【解决方案4】:
          char return_string[250];
          int num_hosts;
          
          if ((num_hosts = hci_scan((char **) & return_string, 0x03)) > 0) {
              //case where one or more devices are found...
          } else {
              //case where zero devices are found...
          }
          

          嗯,hci_scan() 的签名是什么?我的意思是它返回什么?即使您无权访问 hci_scan() 定义,您仍然可以拥有签名,假设它是第三方 api 的一部分。

          看起来 hci_scan() 需要一个指向指针的指针,以便它可以分配自己的内存并返回指针。如果确实如此,您可以这样做

          char * return_string; /* No memory allocation for string */
          int num_hosts;
          
          if ((num_hosts = hci_scan(&return_string, 0x03)) > 0) { /* get back pointer to allocated memory */
              //case where one or more devices are found...
          } else {
              //case where zero devices are found...
          }
          

          但话又说回来,这取决于 hci_scan 试图做什么。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2011-02-02
            • 2013-03-26
            • 2022-11-27
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多