如何判断何时到达 C 数组的末尾? (特别是argv)

发布于 2024-12-15 13:46:31 字数 135 浏览 6 评论 0原文

被问到了一个关于这个的问题,基本上是想出了 argc...

如果你给定的 argv 实际上没有 argc,据我所知,它本质上是指向每个输入参数的相关 char 数组的指针数组,

我实际上将如何进行计数argv 中的指针数量?

been asked a question on this, basically coming up with argc...without actually having argc

if your given argv, which as I understand essentially a array of pointers to the relevant char arrays of each inputted argument,

how would I actually go about counting the number of pointers in argv?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

穿透光 2024-12-22 13:46:32

一般来说,你不能,除非数组被一​​些“停止”值(如 0NULL)明确终止。这就是 argc 存在的原因。指针本身没有与其关联的元素的长度/计数/数量。

当传递指向数组的指针时,您还必须传入元素的数量,或者显式分配过多元素并向数组末尾添加一个“空”元素。

In general, you can't, unless the array is specifically terminated by some "stop" value like 0 or NULL. This is the reason argc exists. Pointers themselves don't have a length/count/number of elements associated with them.

When passing around pointers to arrays, you must necessarily also pass in the number of elements or explicitly allocate one-too-many elements and add a "null" element to the end of the array.

难以启齿的温柔 2024-12-22 13:46:32

我不同意这里有些人的观点。

argv 本身以 null 终止。例如,如果您输入,

$./foobar hello strawberry

您将得到

argv = [%p]  [%p]  [%p]  [NULL]
        |     |     |    
        |     |      \_"strawberry\0"
        |     | 
        |      \_"hello\0"
        |    
         \_"./foobar\0"

换句话说,这种代码将起作用:

while (*argv) {
    printf("%s\n", *argv);
    argv++;
}

尝试一下,看看!

I disagree with some people here.

argv itself is null terminated. For example, if you type

$./foobar hello strawberry

you'll get

argv = [%p]  [%p]  [%p]  [NULL]
        |     |     |    
        |     |      \_"strawberry\0"
        |     | 
        |      \_"hello\0"
        |    
         \_"./foobar\0"

In other words, this sort of code will work:

while (*argv) {
    printf("%s\n", *argv);
    argv++;
}

Try it and see!

巡山小妖精 2024-12-22 13:46:32

你不能。数组结束后就有随机性,你无法准确地区分随机性和真实数据。

You cannot. After the array ends there is randomness, and you cannot accurately distinguish randomness from real data.

香草可樂 2024-12-22 13:46:32

您必须使用 argc,它在提供 argv 时始终存在。 argv 中的最终 char 指针位于 argv[argc-1]

You must use argc, which is always present when argv is furnished. The final char pointer in argv is at argv[argc-1]

一身骄傲 2024-12-22 13:46:31

C 标准规定:

argv[argc] shall be a null pointer.

因此,您始终可以通过测试 0 来检测结束。

The C standard specifies:

argv[argc] shall be a null pointer.

So you can always detect the end by testing for 0.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文