如何在C中声明常量数组参数?

时间:2022-12-06 07:39:55

I can write

我可以写

#include <stdio.h>

int main(const int argc, const char * const * const argv) {
    argv = NULL;
    printf("Hello, world\n");
    return 0;
}

And this doesn’t compile because argv is const (which is good).

这不会编译,因为argv是const(很好)。

However a document I read suggested char * argv[argc + 1] as a better way to declare argv. But how can I make it so this declaration style makes argv itself const?

但是我读到的文档建议使用char * argv [argc + 1]作为声明argv的更好方法。但是我怎么能这样做这个声明样式使argv本身是const?

#include <stdio.h>

int main(const int argc, const char * const const argv[argc + 1]) {
    argv = NULL;
    printf("Hello, world\n");
    return 0;
}

This compiles but I’d really like it not to.

编译,但我真的不喜欢它。

1 个解决方案

#1


3  

See the C standard, 6.7.3p9:

参见C标准,6.7.3p9:

If the specification of an array type includes any type qualifiers, the element type is so- qualified, not the array type. ...

如果数组类型的规范包括任何类型限定符,则元素类型是限定的,而不是数组类型。 ...

So, the const cannot be applied to the array name. Either you use the pointer syntax or live with the non-const pointer. Note that this has no impact for correct code on most architectures.

因此,const不能应用于数组名称。要么使用指针语法,要么使用非const指针。请注意,这对大多数体系结构中的正确代码没有影响。

As argv is a pointer to the first element in both versions, see 6.7.6.3p7, there is in fact no difference between char **argv and char *argv[] arguments. You cannot pass an array (as an array) to a function.

由于argv是指向两个版本中第一个元素的指针,请参见6.7.6.3p7,实际上char ** argv和char * argv []参数之间没有区别。您不能将数组(作为数组)传递给函数。

#1


3  

See the C standard, 6.7.3p9:

参见C标准,6.7.3p9:

If the specification of an array type includes any type qualifiers, the element type is so- qualified, not the array type. ...

如果数组类型的规范包括任何类型限定符,则元素类型是限定的,而不是数组类型。 ...

So, the const cannot be applied to the array name. Either you use the pointer syntax or live with the non-const pointer. Note that this has no impact for correct code on most architectures.

因此,const不能应用于数组名称。要么使用指针语法,要么使用非const指针。请注意,这对大多数体系结构中的正确代码没有影响。

As argv is a pointer to the first element in both versions, see 6.7.6.3p7, there is in fact no difference between char **argv and char *argv[] arguments. You cannot pass an array (as an array) to a function.

由于argv是指向两个版本中第一个元素的指针,请参见6.7.6.3p7,实际上char ** argv和char * argv []参数之间没有区别。您不能将数组(作为数组)传递给函数。