在C中查找字符数组的长度

not*_*33t 50 c arrays

在C中有什么方法可以找到一个Character数组的长度?

我很乐意接受伪代码,但如果他们愿意,我不反对写出来的人

Dan*_*ite 70

如果char数组null终止,

char chararray[10];
size_t len = strlen(chararray);
Run Code Online (Sandbox Code Playgroud)

  • `sizeof()`asnd`strlen()`都返回`size_t`,它与`int`的区别在于它可能更大或更小,当然也是无符号的. (6认同)

Jam*_*lis 15

如果你有一个数组,那么你可以通过将数组的大小除以每个元素的大小(以字节为单位)来找到数组中元素的数量:

char x[10];
int elements_in_x = sizeof(x) / sizeof(x[0]);
Run Code Online (Sandbox Code Playgroud)

对于具体情况char,因为sizeof(char) == 1,sizeof(x)将产生相同的结果.

如果只有一个指向数组的指针,那么就无法找到指向数组中的元素数.你必须自己跟踪.例如,给定:

char x[10];
char* pointer_to_x = x;
Run Code Online (Sandbox Code Playgroud)

没有办法告诉pointer_to_x它它指向一个由10个元素组成的数组.您必须自己跟踪这些信息.

有很多方法可以做到这一点:你可以在变量中存储元素的数量,或者你可以编码数组的内容,这样你就可以通过分析它的内容以某种方式得到它的大小(这实际上是以null结尾的字符串做的:它们'\0'在字符串的末尾放置一个字符,以便您知道字符串何时结束).


小智 9

嗨虽然上面的答案都没问题,但这是我对你的问题的贡献.

//returns the size of a character array using a pointer to the first element of the character array
int size(char *ptr)
{
    //variable used to access the subsequent array elements.
    int offset = 0;
    //variable that counts the number of elements in your array
    int count = 0;

    //While loop that tests whether the end of the array has been reached
    while (*(ptr + offset) != '\0')
    {
        //increment the count variable
        ++count;
        //advance to the next element of the array
        ++offset;
    }
    //return the size of the array
    return count;
}
Run Code Online (Sandbox Code Playgroud)

在函数main中,通过传递数组的第一个元素的地址来调用函数大小.例如:

char myArray[] = {'h', 'e', 'l', 'l', 'o'};
printf("The size of my character array is: %d\n", size(&myArray[0]));
Run Code Online (Sandbox Code Playgroud)

祝一切顺利


dco*_*dco 7

你可以使用 strlen

strlen(urarray);
Run Code Online (Sandbox Code Playgroud)

您可以自己编写代码,以便了解它是如何工作的

size_t my_strlen(const char *str)
{
  size_t i;

  for (i = 0; str[i]; i++);
  return i;
}
Run Code Online (Sandbox Code Playgroud)

如果你想要数组的大小,那么你使用 sizeof

char urarray[255];
printf("%zu", sizeof(urarray));
Run Code Online (Sandbox Code Playgroud)

  • 任何 `strlen()` 都应该返回 `size_t`(无符号)而不是 `int`(有符号)。而`size_t` 的`printf()` 说明符是`"%zu"`(或者`"%zx"` 或`"%zo"` 表示十六进制或八进制)。 (4认同)

one*_*sse 5

如果要使用字符数组的长度sizeof(array)/sizeof(array[0]),如果要使用字符串的长度strlen(array).