C-从函数返回数组 [英] C - Returning an array from a function

查看:46
本文介绍了C-从函数返回数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个函数,该函数以C语言返回一个字符串数组。我在网站上查看了其他一些问题,并尝试了一些解决方案,但似乎没有任何效果。我尝试过(1)只是简单地更改函数以更改数组内容而不是返回它,并且我尝试过(2)显式返回arrayz,但似乎都不起作用。
方法#1:
在一个文件中,函数:

I'm trying to create a function that returns an array of strings in C. I've looked at some other questions on the site and tried some of the solutions, but nothing seems to work. I've tried (1) simply changing the function to change the array contents rather than returning it, and I've tried (2) explicitly returning the arrayz, but neither seems to work. Approach #1: In one file, the function:

 int getArray(int num, char** array)
    {
        int i;
        for (i = 0; i < num; i++)
            array[i] = "whatever";
        return 0;
    }

在另一个文件中,我调用该函数:

In another file, I call the function:

char** array = malloc(sizeof(char*) * num));
getArray(num, files);

当我尝试打印阵列文件的内容时,什么都没有显示。
方法2:
在一个文件中,函数:

When I try printing the contents of the array files, nothing shows up. Approach #2: In one file, the function:

 char** getArray(int num)
    {
        int i;
        char** array = malloc(sizeof(char*) * num));
        for (i = 0; i < num; i++)
            array[i] = "whatever";
        return array;
    }

在另一个文件中,我调用该函数:

In another file, I call the function:

    char** files = getArray(num);

同样,当我尝试打印文件内容时,什么也没有显示。

Again, when I try printing the content of files, nothing shows up.

我已经检查过,并且在其中定义 getFiles()的头文件已包含在我进行调用的文件中。我不确定发生了什么。

I have checked and the header file where getFiles() is being defined has been included in the file where I make the call. I'm not sure what's happening.

推荐答案

您实际上需要为字符串分配空间。您只是为指向字符串的指针分配内存。
在您提供的示例中,您可以使用 strdup 任何字符串分配空间。像这样:

You need to actually allocate space for your strings. You are just allocating memory for pointers to your strings. In the example you provided you can use strdup to allocate space for your whatever string. Like this:

int getArray(int num, char** array)
{
    int i;
    for (i = 0; i < num; i++)
        array[i] = strdup("whatever");
    return 0;
}

这篇关于C-从函数返回数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆