gpt4 book ai didi

c - 你如何在 c 中遍历字符数组的数组?

转载 作者:太空狗 更新时间:2023-10-29 14:57:55 24 4
gpt4 key购买 nike

您是否必须手动遍历数组一次并获取每个字符数组的 strlen 计数,将其求和,使用求和值分配目标,然后再次遍历数组?

如何找到包含字符数组的数组的大小以便迭代它们?

最佳答案

How do you find the size of the array that contains the arrays of characters so you can iterate over them?

有两种方式:

  1. 在变量中分配数组时记录数组中的字符串数。
  2. 在数组末尾分配一个额外的char*,并在其中存储一个空指针作为标记,类似于使用 NUL 字符终止字符串的方式。

换句话说,您在分配数组时必须自己记账,因为 C 不会为您提供所需的信息。如果你按照第二个建议,你可以得到字符串数组中的字符总数

size_t sum_of_lengths(char const **a)
{
size_t i, total;
for (i = total = 0; a[i] != NULL; i++)
total += strlen(a[i]);
return total;
}

在进行实际连接时,不要忘记为 '\0' 保留空间。

关于c - 你如何在 c 中遍历字符数组的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9047166/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com