0

what is the difference of passing an array to a function like this

function(int x[]){

}

or

like this(int x*){

}

what is the difference both ways seem to work

4
Contributors
3
Replies
19
Views
4 Years
Discussion Span
Last Post by deceptikon
0

they are both wrong,

int x[] is often the same as int* x

void function(int x[])
{

}


int main()
{
    int x[20];
    function(x);

    int* y = malloc(20*sizeof(int));
    function(y);
}

Edited by Ancient Dragon

0

They both are same functionally eventhough the syntax is different.

The compiler decay's function(int x[]) into function(int *x)

When you are passing an array to a function, you are implicity passing the address of it invariably.

There is no pass by value when it comes to a function with array as the parameter.

Consider the following program.

#include <stdio.h>

void func (char s[])
{
    printf ("%s", s); 
}

int main()
{
    char a[]="Hello, World";
    func(a);
    return 0;

}

Here the address of the array is passed to the function func

Incase you have a debugger, you can verify when you step into the function call,
where the variable s will hold the address of the array a.

2

There is no pass by value when it comes to a function with array as the parameter.

It's the other way around. There's no pass by reference in C, period. When passing an array, you're passing the address as a pointer by value.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.