-1

I want to pass an arrays index from my function to main. How can I do that? For example:

void randomfunction()
{
    int i;
    char k[20][10];
    for (i=0;i<20;i++)
        strcpy(k[i], "BA");
}
int main(int argc, char *argv[])
{
    int i; for (i=0;i<20;i++) printf("%s",k[i]);
    return 0;
}

I know that for you this is very simple but I've found similar topics and they were too complicated for me. I just want to pass the k array to main. Of course my purpose is not to fill it with "BA" strings...

sarath
  • 513
  • 6
  • 18
GeorgeDavidKing
  • 149
  • 2
  • 3
  • 10
  • Firstly, your code won't compile, is that code meant to be part of `randomfunction`? Second, what do you mean by "pass the k array to main`? Show an example of how `randomfunction` is called and `k` is used in `main`. – etheranger May 04 '14 at 04:13
  • @etheranger what about now? – GeorgeDavidKing May 04 '14 at 04:24
  • Better. It's still not entirely clear (but we can guess) when `randomfunction` is called. Normally "passing a value from `a` to `b`" means that `a` calls `b`. It would of course be a nonsensical thing for `randomfunction` to call `main`, but given the naivety of the question you could have been trying to do that, and would need a different answer. – etheranger May 04 '14 at 04:33

3 Answers3

2

You want to allocate the memory dynamically. Like this:

char** randomfunction() {    
    char **k=malloc(sizeof(char*)*20);
    int i;

    for (i=0;i<20;i++)
        k[i]=malloc(sizeof(char)*10);

    //populate the array

    return k;    
}

int main() {
    char** arr;
    int i;

    arr=randomfunction();

    //do you job

    //now de-allocate the array
    for (i=0;i<20;i++)
        free(arr[i]);        
    free(arr);

    return 0;
}

See about malloc and free.

HelloWorld123456789
  • 5,299
  • 3
  • 23
  • 33
2

Here is another option. This works because structs can be copied around , unlike arrays.

typedef struct 
{
    char arr[20][10];
} MyArray;

MyArray random_function(void)
{
    MyArray k;
    for (i=0;i<sizeof k.arr / sizeof k.arr[0];i++)
       strcpy(k.arr[i], "BA");
    return k;
}

int main()
{
     MyArray k = random_function();
}
M.M
  • 138,810
  • 21
  • 208
  • 365
1

Simplest way:

void randomfunction(char k[][10])
{
    // do stuff
}

int main()
{
    char arr[20][10];
    randomfunction(arr);
}

If randomfunction needs to know the dimension 20, you can pass it as another argument. (It doesn't work to put it in the [] , for historial reasons).

M.M
  • 138,810
  • 21
  • 208
  • 365