首页 > 解决方案 > 如何在 C 函数中分配三重指针的内存

问题描述

我是 C 新手,有一个案例,我想读取一个简单的文本文件,每行一个单词,我想将它保存到一个数组中。但是,我想在函数 main 中声明一个双指针,然后通过引用另一个函数来分配内存并填充双指针。如果不抛出分段错误,我似乎无法让它工作。任何建议将不胜感激。

这是我尝试过的:

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

/*
test.txt = content between the "---"
---
first
second
third
fourth
fifth
sixth
seventh
---
*/

void allocmem (char ***tptr) {

    FILE *infile = fopen("test.txt", "r");
    int bufferLength = 5;
    char *buffer = malloc(sizeof(char) * bufferLength);

    int c, i, row, rows;
    c = i = row = 0;
    rows = 7;

/*
    I want to allocate an array of char strings to store the list from test.txt in
    I have tried different variants here
*/

    tptr = malloc(sizeof(char**) * rows);
    for (int r = 0; r < rows; r++) {
        *tptr[r] = malloc(sizeof(char*) * bufferLength);
    }

/*
    // another attempt
    *tptr = malloc(sizeof(char*) * rows);
    for (int r = 0; r < rows; r++) {
        *tptr[r] = malloc(sizeof(char) * bufferLength);
    }
*/

    while ((c = getc(infile)) != EOF) {

        if (c == '\n') {
            buffer[++i] = '\0';
            printf("buffer: %s\n", buffer);

            // I am also a little unsure how to append my buffer to the pointer array here too
            strcpy(*tptr[row++], buffer);
            memset(buffer, '\0', bufferLength);
            i = 0;
        } else {
            buffer[i++] = c;
        }

    }

    fclose(infile);

}

int main () {

    // double pointer to hold array value from test.txt in
    char **dptr;

    // allocate memory and read test.txt and store each row into the array
    allocmem(&dptr);

/*  
    print each element of dptr here yielding the expected results of:

    first
    second
    third
    fourth
    fifth
    sixth
    seventh
*/

    return 0;
}

标签: cpointersmalloc

解决方案


要回答您的问题,可以通过type ***ptr(如@David C. Rankin 所述)分配三重指针,但这根本不切实际。malloc该函数可以简单地使用or分配内存calloc并存储结果,最后通过取消引用将指向结果指针写入参数给定的指针,例如*argument_ptr = result_pointer. 我重写了代码以避免分段错误。这是代码:

void allocmem (char ***tptr) {
    // The aim of this function is to return the array of strings read from the file
    FILE *infile = fopen("test.txt", "r"); // Read text file
    const int bufferLength = 10, number_of_strings = 7; // Read string 7 times, for a maximum length of 10
    char **array = (char**)calloc(sizeof(char*), number_of_strings); // Allocate memory for a bunch of strings (char*), but the memory for the characters are not initialized
    for (int i = 0; i < number_of_strings; i++){
        char *string = (char*)calloc(sizeof(char), bufferLength); // Memory for the string, a.k.a. character array
        fgets(string, bufferLength, infile); // Read the string (word) from file
        char *c;
        if (c = strchr(string, '\n')) *c = '\0'; // Remove the newline character if exists
        array[i] = string; // Assign the string to the array
    }
    fclose(infile); // Close the file
    *tptr = array; // Return the array created by modifying the given pointer
}

如果不抛出分段错误,我似乎无法让它工作。

第 35 行和第 53 行的分段错误是由错误的取消引用引起的。在第 35 行,您应该简单地使用tptr[r]来访问char**指针,第 53 行也是如此。


推荐阅读