C语言 如何在c中找到char数组的长度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6001661/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 08:39:28  来源:igfitidea点击:

How to find the length of an char array in c

carrays

提问by stelios

I want to find the length of this :

我想找到这个的长度:

char *s[]={"s","a","b"};

it should count 4 with the /0 but the strlen or sizeof(s)/sizeof(char) gives me wrong answers.. How can i find it?

它应该用 /0 计算 4 但 strlen 或 sizeof(s)/sizeof(char) 给了我错误的答案..我怎么能找到它?

回答by Christian Rau

You are making an array of char*and not of char. That's why strlenwon't work. Use

您正在制作一个数组char*而不是char. 这就是为什么strlen行不通。用

sizeof(s) / sizeof(char*) //should give 3

If you want a single string use

如果你想要一个单一的字符串使用

char s[] = "sab";

回答by lhf

sizeof(s) / sizeof(s[0])works no matter what type scontains.

sizeof(s) / sizeof(s[0])无论s包含什么类型都有效。

回答by Naveen

What you have defined is not a string hence there is no NULL terminating character. Here you have declared pointers to 3 separate strings. BTW, you should declare your array as const char*.

您定义的不是字符串,因此没有 NULL 终止字符。在这里,您已经声明了指向 3 个单独字符串的指针。顺便说一句,您应该将数组声明为const char*.

回答by Zaur Nasibov

There is no direct way to determine the length of an array in C. Arrays in C are represented by a continuous block in a memory.

没有直接的方法可以确定 C 中数组的长度。 C 中的数组由内存中的连续块表示。

You must keep the length of the array as a separate value.

您必须将数组的长度保留为单独的值。

回答by atoMerz

strlen works if you terminate your array with null character. You cannot find number of elements in a char array unless you keep track of it. i.e store it in some variable like n. Every time you add member increment n and every time you remove decrement n

如果您使用空字符终止数组,则 strlen 有效。除非您跟踪它,否则您无法在 char 数组中找到元素的数量。即将它存储在一些像n这样的变量中。每次添加成员增加 n 和每次删除减少 n

回答by MByD

Why should it count 4? you have 3 pointers to char in this array, it should count 12 on most 32-bit platforms.

为什么要数4?在这个数组中有 3 个指向 char 的指针,在大多数 32 位平台上它应该是 12。