C语言 如何计算字符串类型数组的大小?

gywdnpxw  于 2023-02-21  发布在  其他
关注(0)|答案(2)|浏览(147)

我目前正在创建一个函数,需要将新的str元素追加到一个已经存在的数组中,因为每个str的大小并不相同,所以我并不真正知道该数组的大小。
我试着使用sizeof()函数,但由于我不知道每个str的大小,所以我认为它不起作用,我还尝试使用我发现的一种技术:

char* liste[]={"one","two","three","four","five"};
int size = *(&liste + 1) - liste; 
printf(size);

而不是一个大小,我得到一个“程序接收信号SIGSEGV”

qxsslcnc

qxsslcnc1#

请记住,C语言中的双引号字符串常量..以及与此相关的所有数组..通常类似于 pointers(对于字符串常量,具体来说,它们类似于char*)。最外层数组的大小是指针的大小乘以元素的数量(所有字符串本身都存储在其他地方)。
如果你想得到元素的数量,* 并且在编译时就知道了 *,你可以使用sizeof(liste)/sizeof(liste[0]);如果在编译时不知道,你必须添加一些其他的方法来跟踪它,比如在末尾添加一个NULL或者一个单独的变量来保存大小。(双引号字符串使用第一个选项:"hello"大致等于['h', 'e', 'l', 'l', 'o', 0]。)
不过,就SIGSEGV而言:printf接受一个字符串(即指针)作为它的第一个参数。当你给予它一个数字时,它试图将它用作指针,头先运行到它不应该访问的内存中,然后操作系统使用SIGSEGV杀死它。打印数字的正确方法类似于printf("%d", my_int)

bgtovc5b

bgtovc5b2#

注意:sizeof(liste)在Windows中将不再返回数组的完整大小,而只返回指针的大小。Windows中的标准库已经悄悄地改变了这一点,以允许使用它们的附加库,如std:array和std::iterator。您将需要使用这些库中的函数或创建自己的方法来计数元素。这是一个示例,适用于那些由于库冲突或其他原因而无法使用std::array或std::iterator的用户。

size_t SizeOfArray(std::string* inComing)
{
  size_t outGoing = 0;
  bool end = false;
  // Validate Array
  if (inComing != NULL)
  {
    // Appended arrays can be valid or not. Sometimes earlier cleanup
    // will link to an empty array location, so check for empty and invalid. 
    while ((!end) && (inComing[outGoing].size() != 0))
    {
      __try
      {
        // if an appended memory location has value, but is not an array
        // you look for the NULL character. For wstrings change '\0' to L'\0'.
        // If the memory location is not valid, it will throw the exception.
        if (inComing[outGoing].c_str()[inComing[outGoing].length()] != '\0')
        {
          // End of array -  if nice empty value
          end = true;
        }
        else
        {
          outGoing++; // Count each valid string in the array
        }
      }
      // This is the blank exception catch to an extra element that is not
      // valid.
      __except (EXCEPTION_EXECUTE_HANDLER)
      {
      // End of array -  if unknown value
      end = true;
      }
    }
  }
  return outGoing; // Return the count
}

相关问题