Xel*_*a95 4 c arrays pointers constants
I'm programming in C and I want to pass an array to a function; this function cannot modify the elements of the array. What is the correct syntax for the arguments of the function?
void func(const Foo array_in[])
Run Code Online (Sandbox Code Playgroud)
or
void func(Foo const array_in[])
Run Code Online (Sandbox Code Playgroud)
or maybe they are the same? Thank you.
You should use pointer to constant in order to handle that:
#include<stdio.h>
void fun(const int *ptr)//pointer to constant - array boils down to pointer when passed to function
{
ptr[0]=9; //ERROR: Read-Only
}
int main(void)
{
int arr[]={1,2,3,4};
fun(arr);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
NOTE: Do not confuse it with constant pointer