Xela95
Xela95

Reputation: 73

How can I pass an array to a function that cannot modify it?

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[])

or

void func(Foo const array_in[])

or maybe they are the same? Thank you.

Upvotes: 4

Views: 1027

Answers (2)

newacct
newacct

Reputation: 122449

First, the declarations const Foo array_in[] and Foo const array_in[] are exactly the same in C.

Second, when the parameter type of a function has "array of T" type, it is automatically adjusted to "pointer to T" type. So the compiler pretends as if you wrote:

void func(const Foo *array_in)

or equivalently

void func(Foo const *array_in)

Note that both const Foo *array_in and Foo const *array_in mean the exact same thing in C (pointer to const Foo). However, Foo * const array_in means something different (const pointer to Foo).

Upvotes: 1

Agrudge Amicus
Agrudge Amicus

Reputation: 1103

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;    
}

NOTE: Do not confuse it with constant pointer

Upvotes: 5

Related Questions