我目前正在创建一个函数,需要将新的str元素追加到一个已经存在的数组中,因为每个str的大小并不相同,所以我并不真正知道该数组的大小。
我试着使用sizeof()函数,但由于我不知道每个str的大小,所以我认为它不起作用,我还尝试使用我发现的一种技术:
char* liste[]={"one","two","three","four","five"};
int size = *(&liste + 1) - liste;
printf(size);
而不是一个大小,我得到一个“程序接收信号SIGSEGV”
2条答案
按热度按时间qxsslcnc1#
请记住,C语言中的双引号字符串常量..以及与此相关的所有数组..通常类似于 pointers(对于字符串常量,具体来说,它们类似于
char*
)。最外层数组的大小是指针的大小乘以元素的数量(所有字符串本身都存储在其他地方)。如果你想得到元素的数量,* 并且在编译时就知道了 *,你可以使用
sizeof(liste)/sizeof(liste[0])
;如果在编译时不知道,你必须添加一些其他的方法来跟踪它,比如在末尾添加一个NULL或者一个单独的变量来保存大小。(双引号字符串使用第一个选项:"hello"
大致等于['h', 'e', 'l', 'l', 'o', 0]
。)不过,就
SIGSEGV
而言:printf
接受一个字符串(即指针)作为它的第一个参数。当你给予它一个数字时,它试图将它用作指针,头先运行到它不应该访问的内存中,然后操作系统使用SIGSEGV
杀死它。打印数字的正确方法类似于printf("%d", my_int)
。bgtovc5b2#
注意:sizeof(liste)在Windows中将不再返回数组的完整大小,而只返回指针的大小。Windows中的标准库已经悄悄地改变了这一点,以允许使用它们的附加库,如std:array和std::iterator。您将需要使用这些库中的函数或创建自己的方法来计数元素。这是一个示例,适用于那些由于库冲突或其他原因而无法使用std::array或std::iterator的用户。