【问题标题】:length of array with repeated '\0', not strlen重复 '\0' 的数组长度,而不是 strlen
【发布时间】:2017-05-14 06:44:42
【问题描述】:

如果我需要找出重复 '\0' 字符的数组的长度,我应该怎么做? strlen 不会有用,因为它只会以 '\0' 停止。在这种情况下,最好的解决方案是什么? 例如我有一个 buf; 现在我不知道长度。我需要找出长度,以便读取其中的全部数据。

编辑:

无符号字符缓冲区[4096];

这个 buf 中有 '\0' 字符。但它发生在数据之间。即使使用 '\0' 字符,我也需要读取数据。 strlen 不会解决目的。那么方法是什么? 这是这里的部​​分问题:lzss decoding EOF character issue

代码就在那里。请看一下。

【问题讨论】:

  • 你是如何声明数组的?
  • 是的,我做到了@Lashane
  • 你的数组长度是 4096
  • 您的问题不在于数组的大小;它是关于 content 的长度,因为它是 your 具有 your 使用要求的内容,只有 you可以知道答案。实际数组的大小很明显:4096 个元素。
  • @ninja.stop 看看'encode(unc_data, compr_data, &payload_len);'。我想知道第三个参数是干什么用的......?

标签: c strlen


【解决方案1】:

在我看来,确定数组大小有 3 种可能性:

  1. 数组被声明为数组。可以使用sizeof 运算符。 (很好,它是comile-time解决的。)

  2. 数组作为指针传递。大小不能从类型确定。它必须以另一种方式提供。

  3. 数组长度可以由其内容决定。这用于 C 字符串,但也可用于其他类型。 (考虑一下,结束标记本身会消耗一个元素。因此,最大长度比容量小一。)

示例代码test-array-size.c:

#include <stdio.h>

/* an array */
static int a[5] = { 0, 0, 0, 0, -1 };

/* a function */
void func(int a1[], int len1, int *a2)
{
  /* size of a1 is passed as len1 */
  printf("a1 has %d elements.\n", len1);
  /* len of a2 is determined with end marker */
  int len2;
  for (len2 = 0; a2[len2] >= 0; ++len2);
  printf("a2 has (at least) %d elements.\n", len2 + 1);
}

/* HOW IT DOES NOT WORK: */
void badFunc(int a3[5])
{
  int len = sizeof a3 / sizeof a3[0]; /* number of elements */
  printf("a3 seems to have %d elements.\n", len);
}

/* the main function */
int main()
{
  /* length of a can be determined by sizeof */
  int size = sizeof a; /* size in bytes */
  int len = sizeof a / sizeof a[0]; /* number of elements */
  printf("a has %d elements (consuming %d bytes).\n", len, size);
  /* Because this is compile-time computable it can be even used for
   * constants:
   */
  enum { Len = sizeof a / sizeof a[0] };
  func(a, Len, a);
  badFunc(a);
  /* done */
  return 0;
}

示例会话:

$ gcc -std=c11 -o test-array-size test-array-size.c 
test-array-size.c: In function 'badFunc':
test-array-size.c:19:20: warning: 'sizeof' on array function parameter 'a3' will return size of 'int *' [-Wsizeof-array-argument]
   int len = sizeof a3 / sizeof a3[0]; /* number of elements */
                    ^
test-array-size.c:17:18: note: declared here
 void badFunc(int a3[5])
                  ^

$ ./test-array-size.exe 
a has 5 elements (consuming 20 bytes).
a1 has 5 elements.
a2 has (at least) 5 elements.
a3 seems to have 1 elements.

$

【讨论】:

    猜你喜欢
    • 2017-08-27
    • 1970-01-01
    • 2019-03-28
    • 1970-01-01
    • 2017-08-16
    • 2014-07-27
    • 1970-01-01
    • 2013-03-27
    • 2021-01-17
    相关资源
    最近更新 更多