[英]How to define array type in C and making it a const pointer (not pointer to const)
I know that I can define array types in C like the following: 我知道我可以在C中定义数组类型,如下所示:
typedef int array_t[123];
This however does not make a declaration 但是,这没有声明
void someFunction(array_t myArray)
constant in the sense that 在某种意义上说是恒定的
myArray=0;
is forbidden inside the function, but 在函数内部是被禁止的,但是
myArray[0]=0;
is allowed. 被允许。
Is there a way to achieve this? 有没有办法做到这一点? If I add a "const" in the type definition or the parameter declaration, I end up with the reverse behavior, where array elements are constant, but the array pointer itself is variable.
如果在类型定义或参数声明中添加“ const”,则最终会出现相反的行为,即数组元素为常量,但数组指针本身为变量。
You can never assign to an array variable, no matter what. 无论如何,您永远都不能分配给数组变量。 While arrays decays to pointers, as long as it hasn't decayed it's no pointer so you can't assign to it.
虽然数组会衰减到指针,但只要它没有衰减,它就不会指向指针,因此您无法为其赋值。
If you want to set all of the array to a specific value, use memset
, or if you want to copy another array use memcpy
. 如果要将所有数组设置为特定值,请使用
memset
,或者如果要复制另一个数组,请使用memcpy
。
After the edit. 编辑后。 The important thing to remember here is that if you pass it as an argument, then it's passed as a pointer and not an array.
这里要记住的重要一点是,如果将其作为参数传递,那么它将作为指针而不是数组传递。
What you can do is to declare the argument as a constant pointer instead of a pointer to constants. 您可以做的是将参数声明为常量指针,而不是指向常量的指针。
Like 喜欢
void someFunction(int * const myArray);
Then you can still modify the elements, but you can't change the actual pointer. 然后,您仍然可以修改元素,但是不能更改实际的指针。
C99 did introduce syntax for declaring constant pointer parameters through "array" syntax C99确实引入了用于通过“数组”语法声明常量指针参数的语法
void foo(int a[const 123]) /* same as `int *const a` */
{
a = NULL; // ERROR
}
As you can see in the above example, const
have to be placed inside the []
. 如上例所示,必须将
const
放在[]
。
However, that const
cannot be embedded into array type "in advance" by using a typedef
declaration for an array type. 但是,不能通过对数组类型使用
typedef
声明将该const
提前嵌入到数组类型中。 It can only be used directly in function parameter list. 它只能直接在功能参数列表中使用。
If you absolutely need have to have an typedef
, use struct to to encapsulate it. 如果您绝对需要
typedef
,请使用struct对其进行封装。 Using typedef
on arrays is not a good idea. 在数组上使用
typedef
不是一个好主意。
typedef struct {
int arr[123];
} array_t;
And then you can do what Joachim Pileborg suggested with const
: 然后您可以使用
const
来执行Joachim Pileborg的建议:
void someFunction(array_t * const myArray)
{
myArray->arr[0] = ...
Additional advantage to this approach is that you can also transmit other data with your object. 这种方法的另一个优点是,您还可以与对象一起传输其他数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.