if the given function is as exp:then how to calculate no of rows in the given 2d array input2
void fun(char *input2[])
{
//calculate no of rows and in each row no of column
}
if the given function is as exp:then how to calculate no of rows in the given 2d array input2
void fun(char *input2[])
{
//calculate no of rows and in each row no of column
}
In general no. In C, it's not possible to calculate the size of an array using only a pointer to it.
However, if you're given a limitation, that the array is terminated by zero(^), then you can count the number of values before the zero using a loop. If it is an array of pointers (such as you have), then the terminator could be a pointer to a specific value. For example, a pointer to zero(^).
Without that limitation, you must store the length in a variable.
(^) you may use any specific value, but zero is a good choice for pointers and characterstrings.
In C, array parameters decay into simple pointers, so you have to design your function to also accept the length of the array:
void fun(char *input2[], int input2Len);
If you also define an array length macro you can call fun
like this:
#define LEN(arr) ((int) (sizeof (arr) / sizeof (arr)[0]))
char *strings[10];
...
fun(strings, LEN(strings));
it is impossible to know the size of an array passed to function as argument, in form of type function(type array[])
, that because array
is a pointer to the first element of it. but there is no information about the last element.
to get over this issue. there are many solutions that we can implement. some of them may alter the implementation of the function itself as passing the size of the array in a second parameter. but if we want to keep function definition untouched. leaves to two possibilities:
1) setting the number of elements on the first item;
2) marking the end of the array (usually is an empty item)
it is almost the second one which is most adopted, here is the code to illustrate that:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int mySizeOfArray(char *input[]){
char **p=input; //p point to the first element of array
while(*p){
p++;//int crementing the pointer
}
return p-input;//return the difference between them
}
/*__________________________________________________________
*/
int main(){
char *input2[]={"First","Second","Third",/*Last*/NULL};
printf("Size of input=%d\n",mySizeOfArray(input2));
return 0;
}