【问题标题】:Detect the last element of a null terminated vector检测空终止向量的最后一个元素
【发布时间】:2019-09-22 09:20:45
【问题描述】:

在使用套接字的文档中有hostent 结构的描述:https://www.gnu.org/software/libc/manual/html_node/Host-Names.html#Host-Names

对于h_addr_list 字段,它表示它是一个以空指针终止的向量。
所以,我尝试做的是:

struct in_addr *addr = (struct in_addr *)hostent->h_addr_list[0];
while (addr != NULL) {
  // ...
  addr++;
}

我预计addr 变量在到达向量中的最后一个元素时为 NULL,因为该元素应该是 NULL 指针。
但在实践中,这不会发生。 addr 永远不会变成 NULL

// hostent->h_addr_list contains 4 meaningful elements
struct in_addr *addr = (struct in_addr *)hostent->h_addr_list[0];
addr++;
addr++;
addr++;
addr == (struct in_addr *)hostent->h_addr_list[3]; // true
addr++;
// here I expected addr to be NULL to terminate the vector, but...
NULL == addr; // false!!!
addr == (struct in_addr *)hostent->h_addr_list[4]; // false

// just to check that it actually NULL terminated
NULL == hostent->h_addr_list[4]; // true
addr = (struct in_addr *)hostent->h_addr_list[4];
NULL == addr; // true

那么,为什么会这样呢?
我做错了什么?
谢谢。

【问题讨论】:

  • 你不能通过增加指针使其变为 NULL。

标签: c vector null-pointer


【解决方案1】:

查看文档:

char **h_addr_list

这是主机的地址向量。 (回想一下,主机可能连接到多个网络,并且每个网络上都有不同的地址。)向量由空指针终止。

h_addr_list 是指向 char 指针的指针,因此最后一个 pointer 将为 NULL,而不是指向指针本身的指针。否则,它必须位于非常特定的内存中,才能在一定数量的增量后为零!做吧:

char **addr_list = hostent->h_addr_list;
while (*addr_list != NULL) {
    // Now *addr points to a valid address
    struct in_addr *addr = (struct in_addr *)*addr_list;

    addr_list++;
}

【讨论】:

    【解决方案2】:

    它是一个指针向量。它是向量中的最后一个元素(指针)为 NULL,而不是该元素的地址。所以试试while (*addr != NULL)

    此外,您需要将 (struct in_addr *) 转换为指针的起始值(以消除警告?)强烈表明您的代码部分是错误的。

    【讨论】:

      猜你喜欢
      • 2012-08-20
      • 2015-01-11
      • 1970-01-01
      • 2012-12-25
      • 1970-01-01
      • 2011-04-14
      • 1970-01-01
      • 1970-01-01
      • 2022-11-26
      相关资源
      最近更新 更多