Curnelious Curnelious - 4 months ago 21
C++ Question

2D arrays as arguments

I have read a book about

C
, and I did try, so please be soft with me.
I am trying to understand how memory really works.

I would like to have some words array like this ( in C) :

char builts[20][10]={"light","temp"}; //should it looks like this ?


Then, I would like to pass that array to a function (in another class)

//some class
char *builtinFunctions;
void Intepreter::setBuiltIns( char *builtins)
{
// here - should I save a copy to builtinFunctions ?? how ?

}


The other class need to have access to that array of words all the time.
Why this is gives error :
intepreter.setBuiltIns(&builts);
?

How would one declare
builtinFunctions
? as a
pointer
or
array
? should it be copied to?

How exactly the whole thing should look like ??

sps sps
Answer

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);
    return 0;
}

 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 */
}

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(arr);
     return 0;
}

void test_2d(char *arr[])
{
     int i;

     /* process each word */
     for (i = 0; arr[i] != NULL; i++) {
         printf("%s\n", arr[i]);

     /* Do something */
     }
}
Comments