从 C 中的函数内部分配字符串数组 [英] Allocate a string array from inside a function in C

查看:12
本文介绍了从 C 中的函数内部分配字符串数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数可以扫描文件并返回行数以及字符串数组中的行数,我的函数如下所示:

I have a function that scans a file and returns the number of the lines along with the lines in a string array, my function looks like this :

int load_lines(char* _file, char** _array){
    FILE *infile;
    char line_buffer[BUFSIZ];
    char line_number;

    infile = fopen(_file, "r");

    ine_number = 0;
    while (fgets(line_buffer, sizeof(line_buffer), infile)) 
        ++line_number;

    fclose(infile);
    _array = malloc (line_number * sizeof(char*));
    infile = fopen(_file, "r");
    line_number = 0;

    while (fgets(line_buffer, sizeof(line_buffer), infile)) {
        _array[line_number] = malloc(strlen(line_buffer) + 1);
        strcpy(_array[line_number], line_buffer);

        //a printf on _array[line_number] works fine here
        ++line_number;
    }

    return line_number;
}

当我这样称呼它时:

char** _array;
line_number = load_lines(inname, _array);

_array[0];

我得到一个分段错误,因为在函数返回后似乎没有分配数组.

I get a segmentation fault since the array seems to be not allocated after the return of the function.

推荐答案

当您将参数传递给函数时,函数总是处理该参数的副本.

When you pass an argument into a function, the function always works on a copy of that argument.

因此,在您的情况下,load_lines 正在处理 _array 的副本.原_array没有修改:

So in your case, load_lines is working on a copy of _array. The original _array is not modified:

char** _array = NULL;
printf("%p
", _array); // Prints "0x0000"
line_number = load_lines(inname, _array);
printf("%p
", _array); // Prints "0x0000"

要修改_array,你需要传递一个指向它的指针:

To modify _array, you need to pass a pointer to it:

int load_lines(char* _file, char*** _array){
    ...
    (*array) = malloc (line_number * sizeof(char*));
    ...
    (*array)[line_number] = malloc(strlen(line_buffer) + 1);
}

char** _array = NULL;
line_number = load_lines(inname, &_array);

[然而,任何时候你发现自己需要一个三重指针(即 ***),是时候重新考虑你的架构了.]

[However, any time you find yourself needing a triple pointer (i.e. ***), it's time to reconsider your architecture.]

这篇关于从 C 中的函数内部分配字符串数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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