Friday, July 31, 2009

Can anybody tell me methods about how to pass a 2d array to a function in c language?

please tell me about function prototype if i have to pass a pointer to array related with a 2d array.which is best method to pass a 2d array to a function?

Can anybody tell me methods about how to pass a 2d array to a function in c language?
arrays in c are really just pre allocated pointers. You have a couple ways you can pass them to a function. you can declare your function to accept a 2d array





void myFunct(int array[5][5]);


to call it --


int myArray[5][5];


myFunct(myArray);





think of an array of integers as a pointer that points to the first integer in the array. when you use an index [ ] you are just telling it the offset from the starting pointer. so you declare an int x[5] array x would be a pointer essentially. if you want to access the third int x[2] that is telling the compiler take the pointer x (a memory location and add the size of integer * 2 to it. Basically it is just pointer math but the compiler does it for you to prevent memory leaks and helps prevent access of non-allocated memory.





you can actually allocate something dynamically and access with the array [] index feature.





int *x; //pointer of type int





//allocate a dynamic array of 5 ints


x = (int*) malloc(sizeof(int) * 5);





x[0] = 1;


//is the same as


*x=1;





x[1] = 2;


//is the same as


*(x + (sizeof(int) *1)) = 2; //manual pointer math











a 2d array is simply a pointer to a pointer.





int my2d[5][5];





the first index is pulling a pointer to the actual array (and since and array is simply a pointer) it's a pointer to a pointer.





if you wanted to pull out individual arrays you could





int my2d[5][5];


int *ptr;





//ptr is now an array of my2d[0][0-4]


ptr = my2d[0]


//ptr[4] is the same as my2d[0][4]





so another way to pass a 2d array would be.





void myFunct(int **array);





called by same


int myArray[5][5];





myFucnt(myArray);
Reply:pass a pointer to the array


No comments:

Post a Comment