Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing dynamically allocated array as a parameter in C

Tags:

arrays

c

matrix

So... I have a dynamically allocated array on my main:

int main()
{
    int *array;
    int len;

    array = (int *) malloc(len * sizeof(int));
    ...
    return EXIT_SUCCESS;
}

I also wanna build a function that does something with this dynamically allocated array. So far my function is:

void myFunction(int array[], ...)
{
   array[position] = value;
}

If I declare it as:

void myFunction(int *array, ...);

Will I still be able to do:

array[position] = value;

Or I will have to do:

*array[position] = value;

...?

Also, if I am working with a dynamically allocated matrix, which one is the correct way to declare the function prototype:

void myFunction(int matrix[][], ...);

Or

void myFunction(int **matrix, ...);

...?

like image 393
Thi G. Avatar asked Dec 21 '22 00:12

Thi G.


1 Answers

If I declare it as:

void myFunction(int *array, ...);

Will I still be able to do:

array[position] = value;

Yes - this is legal syntax.

Also, if I am working with a dynamically allocated matrix, which one is correct to declare the function prototype:

void myFunction(int matrix[][], ...);

Or

void myFunction(int **matrix, ...);

...?

If you're working with more than one dimension, you'll have to declare the size of all but the first dimension in the function declaration, like so:

void myFunction(int matrix[][100], ...);

This syntax won't do what you think it does:

void myFunction(int **matrix, ...);
matrix[i][j] = ...

This declares a parameter named matrix that is a pointer to a pointer to int; attempting to dereference using matrix[i][j] will likely cause a segmentation fault.

This is one of the many difficulties of working with a multi-dimensional array in C.

Here is a helpful SO question addressing this topic: Define a matrix and pass it to a function in C

like image 130
Tom Avatar answered Dec 24 '22 02:12

Tom