You can pass the 2 day array by just using its name while calling a function, like:
test_2d(builts);
You can either pass the total number of words as a separate argument, or alternatively, you can make a special word to indicate end of your array. For instance, I have used a special word "\0"
to indicate that this marks the end of array. Overall the code looks like.
#include<stdio.h>
#include<string.h>
int main(void)
{
char builts[20][10]={"light","temp", "\0"};
test_2d(builts); /* without passing total number of args; depends on special word at the end */
test_2d_num(builts, 2); /* also pass total num of elements as argument */
return 0;
}
/* This needs a special word at the end to indicate the end */
void test_2d(char builts[][10])
{
int i;
char tmp[10];
/* just print the words from word array */
for (i=0; *builts[i] != '\0'; i++ )
printf("%s\n", builts[i]);
/* also try copy words to a tmp word and print */
for (i=0; *builts[i] != '\0'; i++ ) {
strcpy(tmp, builts[i]);
printf("%s\n", tmp);
}
/* Do something */
}
/* Also get total number of elements as a parameter */
void test_2d_num(char builts[][10], int tot_elem)
{
int i;
/* Process each word from the array */
for (i = 0; i < tot_elem; i++) {
printf("%s\n", builts[i]);
/* Do something */
}
}
Note that this function can only process arrays like, builts[][10]
, and not builts[][11]
, or builts[][9]
.
If you want want a generic function, then you need to store the addresses of individual words in an char *arr[]
and pass this array to the function. Like
int main()
{
/* store the addresses of individual words in an `char *arr[] */
char *arr[] = {"hello", "this", "that", NULL};
test_2d_gen(arr);
return 0;
}
void test_2d_gen(char *arr[])
{
int i;
/* process each word */
for (i = 0; arr[i] != NULL; i++) {
printf("%s\n", arr[i]);
/* Do something */
}
}