C-计数元素(绑定检查)-数组 [英] C - Count elements (bound check) - array

查看:71
本文介绍了C-计数元素(绑定检查)-数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法计算指向字符串的指针数组中的元素?,其中元素im引用其中的每个单词或短语,下面是一个包含3个数组的示例元素(在这种情况下为每个短语).

is there any way to count the elements in an array of pointers to strings? with elements im refering to every word or phrase in it, here is an example of an array with 3 elements (each phrase in this case).

char *s[] = {
    "To err is human...",
    "But to really mess things up...",
    "One needs to know C!!",
};

因此,这里的数组有3个位置(即3个元素),每个位置都指向一个内存地址,该地址是String的开头,但仍然很难确定数组是否到达结尾,因此我添加了第四个元素"\ 0",因此最后它将有2个空字符,然后实现此功能.

So here the array has 3 positions (that would be 3 elements), each pointing to a memory address which is the beginning of a String but it was still difficut to determine whether the array reached the end or not, so I added a fourth element '\0', so at the end it would have 2 null characters and then implemented this function.

int cantidadElementos(char *arr){

  int count=0;
  while(*arr!='\0'){
      while(*arr!='\0'){
          arr++;
      }
      arr++;
      if(*arr!='\0'){
          count++;
      }
  }
return count;
}

我试图做的是绑定检查,所以我发现,如果我使用数组中每个指针的地址,那么我可以看到字符串的地址,然后查看最后一个值是否为'\ 0' (以检查字符串是否到达末尾),但这是不可能的,因为数组的下一个内存地址可能包含垃圾值,因此我想出了在数组末尾添加另一个null字符,然后检查是否有一个双'\ 0'.

What I try to do is bound checking, so I figured out that if I use the address of each pointer in the array I could then see the address of the string, and then see if the last value is '\0' (to check if the string reached the end), but that could not be possible since the next memory address of the array could contain garbage values, so I camed up with adding another null character at the end of the array, and then checking if there is a double '\0'.

我只是觉得这个解决方案太可怕了(可行,但仍然很可怕). 这可能适合文本处理器,因为我只需要多出2个字节的内存来确定文本是否已结束.

I just find this solution horrible (works, but still horrible). This could suit for a text processor, since it is just 2 bytes more of memory that I would use to determine whether the text has reached end or not.

所以回到我的问题,是否有任何方法可以计算指向字符串的指针数组中的元素?我已经进行了很多搜索,无法找到更好的解决方案.

So going back to my question, is there any way to count the elements in an array of pointers to string? I have been searching a lot and couldn't came up with a better solution.

推荐答案

对此进行测试:

const char *s[] = {"To err is human...",    "But to really mess things up...",  "One needs to know C!!"};
printf("%d\n",sizeof(s)/sizeof(*s));

这篇关于C-计数元素(绑定检查)-数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆