如何打印char **

时间:2016-10-19 19:33:17

标签: c pointers

我有一个读取文件并将行分配给char **的方法。但是当我尝试打印它的第一个元素时,它会打印随机字符。可能有什么问题?

int main()
{
     char **lines_from_file = readFromFile(file_name);
     obeyCommands(lines_from_file);
     return 0;
}

void obeyCommands(char **command_lines)
{
    printf("%s", command_lines[0]);
}

char** readFromFile(char *file_name)
{
    int size;
    int c;
    char *buffer;
    char** all_lines= (char**)malloc(sizeof(char*));

    FILE *f = fopen(file_name, "r");
    if(f)
    {
        int i=0;
        do   // read all lines in file
        {
            size = 0;
            buffer = (char *)malloc(size+1);
            do  // read one line
            {
                c = fgetc(f);
                if(c != EOF) buffer[size++] = (char)c;
                buffer = (char*)realloc(buffer, size+1);
            }
            while(c != EOF && c != '\n');

            *(all_lines+i) = (char*)malloc(sizeof(buffer));
            **(all_lines+i) = *buffer;
            i++;
            all_lines = (char**)realloc(all_lines, sizeof(char*) * i);

        }
        while(c != EOF);
        fclose(f);
    }
    free(buffer);
    return all_lines;
}

1 个答案:

答案 0 :(得分:3)

问题1

问题在于:

        **(all_lines+i) = *buffer;

只复制buffer中的一个字符。因此,all_lines中的所有字符串都不会以空值终止。

您应该替换以下行:

        *(all_lines+i) = (char*)malloc(sizeof(buffer));
        **(all_lines+i) = *buffer;

通过

        all_lines[i] = buffer;

问题2

我看到的下一个问题是:

        all_lines = (char**)realloc(all_lines, sizeof(char*) * i);

在循环的第一次迭代中,i为1.因此,该行与以下内容相同:

        all_lines = (char**)realloc(all_lines, sizeof(char*));

这不是你想要的。你想要

        all_lines = (char**)realloc(all_lines, sizeof(char*) * 2);

因为您将在下一次迭代中使用all_lines[1]。那条线必须是:

        all_lines = (char**)realloc(all_lines, sizeof(char*) * (i+1));