Passing multidimensional arrays as function arguments in C *

Question

In C can I pass a multidimensional array to a function as a single argument when I don't know what the dimensions of the array are going to be ?

In addition my multidimensional array may contain types other than strings.

Answer

You can do this with any data type. Simply make it a double pointer:

typedef struct {
int myint;
char* mystring;
} data;

data** array;

But don't forget you still have to malloc the variable, and it does get a bit complex:

//initialize
int x,y,w,h;
w = 10; //width of array
h = 20; //height of array

//malloc the 'y' dimension
array = malloc(sizeof(data*) * h);

//iterate over 'y' dimension
for(y=0;y<h;y++){
//malloc the 'x' dimension
array[y] = malloc(sizeof(data) * w);

//iterate over the 'x' dimension
for(x=0;x<w;x++){
//malloc the string in the data structure
array[y][x].mystring = malloc(sizeof(char) * 50); //50 chars

//initialize
array[y][x].myint = 6;
array[y][x].mystring = "w00t";
}
}

The code to deallocate the structure looks similar - don't forget to call free() on everything you malloced! (Also, in robust applications you should check the return of malloc().)

Now let's say you want to pass this to a function. You can still use the double pointer, because you probably want to do manipulations on the data structure, not the pointer to pointers of data structures:

int whatsMyInt(data** arrayPtr, int x, int y){
return arrayPtr[y][x].myint;
}

Call this function with:

printf("My int is %d.\n", whatsMyInt(array, 2, 4));

Output:

My int is 6.
< br > via < a class="StackLink" href=" http://stackoverflow.com/questions/4051/" >Passing multidimensional arrays as function arguments in C< /a>
Share on Google Plus

About Cinema Guy

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment