如何计算**指针的索引

时间:2015-02-20 06:19:43

标签: c

我是c编程的初学者,我想使用的是地址列表 hostent结构,但我无法计算有多少地址  我的代码是

int main (int argc,  char *argv[])
{
  int i;
  struct hostent  *host_info;
  struct in_addr *address;
  if(argc <2)
    {
      printf("USAGE: %s <hostname>\n",argv[0]);
      exit(1);
    }
  host_info=gethostbyname(argv[1]);
  if(host_info==NULL)
    {
      printf("couldn't lookup %s\n",argv[1]);

    }
  else
    {
      for(i=0;i<??????????;i++){
      address=(struct in_addr *)(host_info ->h_addr_list[i]);
      printf("%s  has address %s\n",argv[1],inet_ntoa(*address));
      }
    }

}

2 个答案:

答案 0 :(得分:1)

host_addr结构不包含地址列表的长度。相反,地址列表中的最后一个条目是0(NULL)。所以循环host_info->h_addr_list[i] != 0

答案 1 :(得分:0)

你可以这样做,

 while(host_info ->h_addr_list[i]  != NULL){
  address=(struct in_addr *)(host_info ->h_addr_list[i]);
  printf("%s  has address %s\n",argv[1],inet_ntoa(*address));
  }