从函数返回字符串数组

发布于 2024-11-10 03:20:16 字数 619 浏览 5 评论 0原文

我需要返回一个 char** 但当我尝试这样做时,编译器告诉我我想返回局部变量的地址。我怎样才能做到这一点?我知道我应该为这个变量分配空间,但是如何分配空间呢?这是我的代码,但第二个 printf 没有出现,并且该函数不返回任何内容:

char** parse_cmd(const char* cmdline) {
char** arguments = (char**)malloc(100);
int i;
int j=0, k=0;
printf("%s\n", cmdline);

for(i=0; i<100; i++) {
    arguments[i] = malloc(100);
}

for(i = 0; i < strlen(cmdline); i ++) {
    if(cmdline[i] != ' ') {
        arguments[j][k] = cmdline[i];
        k++;
    } else {
        arguments[j][k] = '\0';
        j++;
        k = 0;
    }
}

printf("%s\n", arguments[1]);

return arguments;
}

I need to return a char** but when I try to do this, the compiler tells me that I want to return the address of a local variable. How can I do that? I know that I should allocate space for this variable but how? Here is my code, but the second printf doesn't appear and the function returns nothing:

char** parse_cmd(const char* cmdline) {
char** arguments = (char**)malloc(100);
int i;
int j=0, k=0;
printf("%s\n", cmdline);

for(i=0; i<100; i++) {
    arguments[i] = malloc(100);
}

for(i = 0; i < strlen(cmdline); i ++) {
    if(cmdline[i] != ' ') {
        arguments[j][k] = cmdline[i];
        k++;
    } else {
        arguments[j][k] = '\0';
        j++;
        k = 0;
    }
}

printf("%s\n", arguments[1]);

return arguments;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

落花随流水 2024-11-17 03:20:16

您需要进行多次分配。第一个用于 char**,然后用于每个 char*。例如类似的东西

  char **args = (char**)malloc(100);
  int i;
  for (i=0; i<100; i++) 
    args[i] = malloc(100);

  // Rest of program

  return args;

You need to do multiple allocations. The first for the char** and then for each of the char*. E.g. something like

  char **args = (char**)malloc(100);
  int i;
  for (i=0; i<100; i++) 
    args[i] = malloc(100);

  // Rest of program

  return args;
苏璃陌 2024-11-17 03:20:16

这是我组装并测试的代码。它对 argv 参数列表和组装的每个参数都使用动态内存分配。函数release_cmd()释放分配的空间。函数cleanup()是内部函数,它在失败时释放分配的空间,然后返回空双指针。这简化了错误处理。 prompt() 函数和 main() 中有一个最小的测试工具。我还没有在 valgrind 下运行,但是 malloc() 的 MacOS X 实现经常发现问题,所以我有一定的信心不存在严重的内存滥用 - 但有可能是差一泄漏。我还没有通过伪造分配失败来测试 cleanup() 代码。

#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void release_cmd(char **argv)
{
    for (size_t i = 0; argv[i] != 0; i++)
        free(argv[i]);
    free(argv);
}

static char **cleanup(size_t argc, char **argv)
{
    argv[argc] = 0;
    release_cmd(argv);
    return 0;
}

char **parse_cmd(const char* cmdline)
{
    size_t argc = 2;
    char **argv = malloc(argc * sizeof(char *));

    if (argv == 0)
        return 0;

    size_t j = 0;  // Index into argv
    size_t len = strlen(cmdline);

    for (size_t i = 0; i < len; i++)
    {
        while (isspace(cmdline[i]))
            i++;
        if (cmdline[i] == '\0')
            break;
        if (j > argc - 2)
        {
            size_t newc = (argc * 2);
            char **newv = realloc(argv, newc * sizeof(char *));
            if (newv == 0)
                return cleanup(argc, argv);
            argv = newv;
            argc = newc;
        }
        size_t argl = 2;    // Length of argument string
        argv[j] = malloc(argl);
        size_t k = 0;       // Index into argv[j]
        while (cmdline[i] != '\0' && !isspace(cmdline[i]))
        {
            if (k > argl - 2)
            {
                size_t newl = argl * 2;
                char  *news = realloc(argv[j], newl);
                if (news == 0)
                    return cleanup(argc, argv);
                argv[j] = news;
                argl    = newl;
            }
            argv[j][k++] = cmdline[i++];
        }
        argv[j][k] = '\0';
        argv[j] = realloc(argv[j], k+1);    // Shrink to fit!
        j++;
    }
    argv[j] = 0;
    argv = realloc(argv, (j+1)*sizeof(*argv));  // Shrink to fit!

    return argv;
}

static int prompt(const char *prompt, char *buffer, size_t bufsiz)
{
    printf("%s", prompt);
    return (fgets(buffer, bufsiz, stdin) != 0);
}

int main(void)
{
    char line[1024];

    while (prompt("cmd? ", line, sizeof(line)) != 0)
    {
        char **argv = parse_cmd(line);
        char **args = argv;
        while (*args)
            puts(*args++);
        release_cmd(argv);
    }
    putchar('\n');
    return 0;
}

Here's the code I assembled - and tested. It uses dynamic memory allocation for both the argv argument list and for each argument as it is assembled. The function release_cmd() releases the allocated space. The function cleanup() is internal and releases allocated space on a failure, before returning a null double-pointer. This simplifies the error handling. There's a minimal test harness in the prompt() function and main(). I haven't run in under valgrind, but the MacOS X implementation of malloc() quite often spots problems so I'm moderately confident there's no gross memory abuse - but there could be an off-by-one leak. I haven't tested the cleanup() code by faking an allocation failure.

#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void release_cmd(char **argv)
{
    for (size_t i = 0; argv[i] != 0; i++)
        free(argv[i]);
    free(argv);
}

static char **cleanup(size_t argc, char **argv)
{
    argv[argc] = 0;
    release_cmd(argv);
    return 0;
}

char **parse_cmd(const char* cmdline)
{
    size_t argc = 2;
    char **argv = malloc(argc * sizeof(char *));

    if (argv == 0)
        return 0;

    size_t j = 0;  // Index into argv
    size_t len = strlen(cmdline);

    for (size_t i = 0; i < len; i++)
    {
        while (isspace(cmdline[i]))
            i++;
        if (cmdline[i] == '\0')
            break;
        if (j > argc - 2)
        {
            size_t newc = (argc * 2);
            char **newv = realloc(argv, newc * sizeof(char *));
            if (newv == 0)
                return cleanup(argc, argv);
            argv = newv;
            argc = newc;
        }
        size_t argl = 2;    // Length of argument string
        argv[j] = malloc(argl);
        size_t k = 0;       // Index into argv[j]
        while (cmdline[i] != '\0' && !isspace(cmdline[i]))
        {
            if (k > argl - 2)
            {
                size_t newl = argl * 2;
                char  *news = realloc(argv[j], newl);
                if (news == 0)
                    return cleanup(argc, argv);
                argv[j] = news;
                argl    = newl;
            }
            argv[j][k++] = cmdline[i++];
        }
        argv[j][k] = '\0';
        argv[j] = realloc(argv[j], k+1);    // Shrink to fit!
        j++;
    }
    argv[j] = 0;
    argv = realloc(argv, (j+1)*sizeof(*argv));  // Shrink to fit!

    return argv;
}

static int prompt(const char *prompt, char *buffer, size_t bufsiz)
{
    printf("%s", prompt);
    return (fgets(buffer, bufsiz, stdin) != 0);
}

int main(void)
{
    char line[1024];

    while (prompt("cmd? ", line, sizeof(line)) != 0)
    {
        char **argv = parse_cmd(line);
        char **args = argv;
        while (*args)
            puts(*args++);
        release_cmd(argv);
    }
    putchar('\n');
    return 0;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文