简体   繁体   English

如何将数组从函数“返回”到c中的main

[英]How to “return” an array from a function to main in c

I want to pass an arrays index from my function to main. 我想将数组索引从我的函数传递给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. 我只想将k数组传递给main。 Of course my purpose is not to fill it with "BA" strings... 当然,我的目的不是用“ BA”字符串填充它。

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 . 查看有关mallocfree

Here is another option. 这是另一种选择。 This works because struct s can be copied around , unlike arrays. 之所以struct是因为struct可以在数组周围复制,这与数组不同。

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

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. 如果randomfunction需要知道20的维数,则可以将其作为另一个参数传递。 (It doesn't work to put it in the [] , for historial reasons). (出于历史原因,将其放入[]无效)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM