简体   繁体   English

从C函数获取2D字符数组

[英]Getting 2d char array from function in c

I want to split my char string by space and here is my code.(reference to others) 我想按空格分割我的字符字符串,这是我的代码。(参考其他人)

void main() {
    char origin_str[] = "How are you";
    int n_segs = Words_counts(origin_str);
    char **split_array = malloc(n_segs * sizeof(char*));
    split_array = split_str_to_array(origin_str);
    ..... //do something
    free(split_array);
}

and the split_str_to_array function: 和split_str_to_array函数:

char **split_str_to_array(const char strr[]) {
    char **res = NULL;
    char * p = strtok(strr, " ");
    int n_spaces = 0;

    while (p) {
        res = realloc(res, sizeof(char*) * ++n_spaces);
        if (res == NULL)
            exit(-1); 

        res[n_spaces - 1] = p;
        p = strtok(NULL, " ");
    }
    res = realloc(res, sizeof(char*) * (n_spaces + 1));
    res[n_spaces] = 0;
    return res;
}

It works well, butI'm confused with the usage of getting char array from the split_str_to_array function. 它运作良好,但是我对从split_str_to_array函数获取char数组的用法感到困惑。

Should I use free(res) in the split function?If yes, how do I return the char array? 我应该在split函数中使用free(res)吗?如果是,如何返回char数组? Declaring a new one with known length to return? 声明一个新的已知长度的返回?

I'm afraid of memory using problems in the split function. 我担心内存会在split函数中使用问题。 Or, a better way to do the same? 还是更好的方法来做到这一点?

very appreciated for your help. 非常感谢您的帮助。

The usage of free() is correct. free()的用法是正确的。

Free what you allocated if not needed any more, by passing to free() what had been returned by the allocating function. 通过将由分配函数返回的内容传递给free()free()不再需要的内容。

However the allocation in main() is useless 但是main()的分配是没有用的

char **split_array = malloc(n_segs * sizeof(char*));

as in the next line 如下一行

split_array = split_str_to_array(origin_str);

you overwrite what had been assigend to split_array . 您将覆盖已分配给split_array

Doing so you lose what had been returned by malloc() so you cannot free it anymore and with this introduce a memory leak. 这样做会丢失malloc()返回的内容,因此您将无法再释放它,从而导致内存泄漏。

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

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