Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arguments in a function prototype

My question is: when i write a function prototype in C like this:

void foo(int *vector);

It's the same thing to do:

void foo(int vector[MAX_LENGTH]);

To the function, is passed always as a pointer? The code it's the same? Thanks in advance.

like image 205
user393821 Avatar asked Dec 03 '22 12:12

user393821


2 Answers

This is subtle. Arrays in C are not pointers, but C does not allow arrays to be passed as function parameters. So when you have void foo(int vector[MAX_LENGTH]);, essentially all you're doing is telling other programmers (and your future self) that this function expects an array of MAX_LENGTH to be passed to it. The compiler won't help you. It will silently cast your array to a pointer.

This explains it pretty well.

like image 164
nmichaels Avatar answered Dec 24 '22 15:12

nmichaels


Yes an array type is implicitly converted to a pointer type when passed to a function.

So

void foo(int *a) and void foo(int a[]) are identical.

You can easily check that using sizeof() operator inside the function definition

For example

void foo(int a[])
{
   std::cout<<sizeof(a); //prints sizeof(int*)
}

int main()
{

   int a[]={1,2,3,4};
   foo(a);
}

EXTRA (Printing size of an array inside a function)

[C++ Only]

 template<typename T,size_t n>
 void size_of_array(T (&a)[n]) //Array passed by reference. Template argument deduction 
 {
    std::cout<<sizeof(a); //prints sizeof(n*sizeof(int))
 }

 int main()
 {
      int a[]={1,2,3,4,5};
      size_of_array(a);
 }
like image 39
Prasoon Saurav Avatar answered Dec 24 '22 16:12

Prasoon Saurav