将const关键字添加到作为参数传递给函数的数组中 [英] Adding const keyword to an array passed as a parameter to function

查看:143
本文介绍了将const关键字添加到作为参数传递给函数的数组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以将const关键字添加到作为参数传递给函数的数组中?

Is there any way that I can add const keyword to an array passed as a parameter to function:

void foo(char arr_arg[])

如果将const放在char(void foo(const char arr_arg[]))之前或char(void foo(char const arr_arg[]))之后,则意味着char是常量,而不是arr_arg.

If I place const before char (void foo(const char arr_arg[])) or after char(void foo(char const arr_arg[])), that would mean than it's char which is constant, not the arr_arg.

我只有阅读在幕后将作为参数发送给函数的数组表示为指针,因此void foo(char arr_arg[])void foo(char* ptr_arg)相同. 考虑到这一点,我可以将函数重写为void foo(char * const ptr_arg),以使其恰好是我想要实现的目标.

I have just read that under the hood an array sent as a parameter to function is represented as a pointer, so void foo(char arr_arg[]) is the same as void foo(char* ptr_arg). Taking it into account, I may rewrite the function as void foo(char * const ptr_arg) for it to be exactly what I want to achieve.

但是我想知道是否有一种方法可以在此声明void foo(char arr_arg[])中添加const关键字,使其与void foo(char * const ptr_arg)相同(并且不是 void foo(char const * ptr_arg)void foo(const char * ptr_arg))?

But I want to know if there is a way to add const keyword in this declaration void foo(char arr_arg[]) for it to be the same as void foo(char * const ptr_arg) (and not void foo(char const * ptr_arg) or void foo(const char * ptr_arg))?

我只想了解是否存在使用数组表示法[]使arr_arg不变的语法.

I just want to understand if there is a syntax to make arr_arg constant with array notation [].

推荐答案

在C语言中,您必须将const 插入[]之间,但是对于一个没有准备的人来说可能很奇怪

In C you have to put const between the [], however strange that might look to an unprepared person

void foo(char arr_arg[const]);

这是新" C99特定语法.在C89/90或C ++中,无法使用数组"语法完成此操作,因此,您必须切换到等效的指针"语法,如David的回答所示.

This is "new" C99-specific syntax. In C89/90 or C++ there no way to do it with "array" syntax, so you have to switch to the equivalent "pointer" syntax, as suggested in David's answer.

这篇关于将const关键字添加到作为参数传递给函数的数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆