繁体   English   中英

从C函数返回数组

[英]Returning an array from a C-function

我目前正在编写一个需要C函数返回数组的应用程序。 我已经读到C函数不能直接返回数组,而只能返回指向数组的指针,无论如何我还是无法使它起作用。 我正在发送一个带有几个数值的字符串,这些数值必须放入数组中。

我的代码如下所示,主要功能是:

int main() {
    char arr[3] = {0};
    char *str = "yaw22test242test232";
    foo(arr,3,str);

    printf("%d\n",arr[0]);

    return 0;
}

我想让foo函数返回分别在数组位置0、1和2上分别为22、242和232的数组。 foo函数中的算法在主程序中使用时可以正常工作,但不能以这种方式工作。 有什么办法可以解决此问题? 我究竟做错了什么? foo函数如下所示:

void foo(char *buf, int count, char *str) {
    char *p = str;
    int k = 0;

    while (*p) { // While there are more characters to process...
        if (isdigit(*p)) { // Upon finding a digit, ...
            double val = strtod(p, &p); // Read a number, ...
            //printf("%f\n", val); // and print it.
            buf[1-count-k] = val;
            k++;
        } else { // Otherwise, move on to the next character.
            p++;
        }
    }
}

好吧,您在这里越界越好:

buf[1-count-k] = val;

也许您的意思是buf[k] = val; 然后检查if( k >= count )以结束循环。

由于char *buf通常不能表示大于127的值,因此应使用足够大的整数类型或双精度类型,否则赋值buf[*] = val; 从double类型到char类型,将导致未定义的行为。

看起来您想将字符串中的数字提取为double ,但是您正在尝试将它们存储在char数组中。 这甚至不编译。

因此,首先,使用适当的缓冲区:

int main() {
    double arr[3] = {0};
    /* ... */
}

并更新foo()的参数声明:

void foo(double *buf, int count,char *str) { ... }

然后解决此问题:

buf[1-count-k] = val;

您可能想要一些简单的东西:

buf[k++] = val;

最后,您可能需要返回k以便调用者有机会知道向数组中写入了多少个数字。 因此, foo将如下所示:

size_t foo(double *buf, int count,char *str) {
    char *p = str;
    size_t k = 0;

    while (*p) { // While there are more characters to process...
        if (isdigit(*p)) { // Upon finding a digit, ...
            double val = strtod(p, &p); // Read a number, ...
            //printf("%f\n", val); // and print it.
            buf[k++] = val;
        } else { // Otherwise, move on to the next character.
            p++;
        }
    }
    return k;
}

请注意,索引数组的正确类型是size_t ,而不是int size_t保证足够宽,可以容纳任何数组的大小,因此,如果您希望代码使用任意长的数组,则应该使用size_t对数组进行索引。

我建议使用类似矢量的结构而不是数组。 已经有许多实现(请参阅C的GLib列表)。 但是,如果您想“自己动手”,请尝试类似的操作:

typedef struct
{
    char** data;
    int size;

} str_vector;

您可以在其中动态分配str_vector及其data成员,然后返回它。 我将不做过多介绍,因为互联网上有很多教程,我相信您可以在几秒钟内在Google / Bing / Whatever中找到它们:)

暂无
暂无

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

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