初始化二維字符串動態數組並通過引用傳遞

用戶3138594

我正在嘗試學習 C 指針傳遞。所以請原諒我的無知。

我想在函數中分配一個二維動態分配的字符串數組。函數簽名是無效的,所以參數是通過引用的。

測試文件包含這兩行。

I am testing.
This is not an empty file.

這是我到目前為止所做的。

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

void read_lines(FILE *fp, char** lines, int *num_lines) {
  ssize_t read;
  char * line = NULL;
  size_t len = 0;
  *num_lines = 0;


  while ((read = getline(&line, &len, fp)) != -1) {
    if (*num_lines == 0) {
      // For the first time it holds only one char pointer
      *lines = malloc(sizeof(char *));
    } else {
      // Every time a line is read, space for next pointer is allocated
      *lines = realloc(*lines, (*num_lines) * sizeof(char *));
    }
    // allocate space where the current line can be stored
    *(lines + (*num_lines)) = malloc(len * sizeof(char));
    // Copy data
    strcpy(*(lines + (*num_lines)), line);
    printf("Retrieved line of length %zu:\n", read);
    printf("%s\n", line);
    (*num_lines)++;
    // After first line subsequent lines get truncated if I free
    // the storage here, then subsequent lines are not read completely
    //if (line) {
    //  free(line);
    //}
  }  
  if (line) {
    free(line);
  }

}
int main(void)
{
    FILE * fp;
    char *array;
    int num_lines;
    fp = fopen("file.txt", "r");
    if (fp == NULL)
        exit(EXIT_FAILURE);
    read_lines(fp, &array, &num_lines);
    printf("After returning\n");
    // Intend to access as array[0], array[1] etc
    // That's not working
    // If I access this way then I get seg violation after first line
    printf("%s\n", &array[0]);
    fclose(fp);
}

我的問題與代碼內聯:

  • 為什麼我不能line在 while 循環內釋放存儲空間
  • 如何訪問返回的二維數組mainarray[0] array[1]似乎不起作用?我想做類似的事情。
  • 為什麼我現在的做法會產生段錯誤?

更正的代碼將幫助我理解。此外,任何人都可以提供任何很好的參考來為 C 闡明這些概念,我們將不勝感激。

黃托德

如果free(line)while循環中,你必須重新設置lineNULLlen0,下一個調用之前getline否則,getline會認為line是 size 的有效緩衝區len,並可能嘗試寫入它,這實際上是現在所謂的“懸空指針”。

realloc線條,大小應該是(*num_lines + 1) * sizeof(char *),多了一個元素需要被分配給持有剛剛讀線。

array變量char*,其地址被佔用和assiged到參數linesread_lines所以,lines是的地址array,而*lines只是array自己。

// allocate `char*[1]`
*lines = malloc(sizeof(char *));

// allocate `char*[N]` with N=`*num_lines`
*lines = realloc(*lines, (*num_lines) * sizeof(char *));

您將 a 分配char*[]array,實際上是 a char*

因此,如果您希望函數按參數返回字符串數組(即char*[]char**),則必須使參數成為指向字符串數組(即char***的指針

#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>

void read_lines(FILE * fp, char*** lines, int* num_lines) {
    ssize_t read;
    char* buffer = NULL;
    size_t buffer_len = 0;
    *num_lines = 0;

    while ((read = getline(&buffer, &buffer_len, fp)) != -1) {
        // `*lines` is actually `array`,
        // modify `*lines` will effectively modify `array`
        if (*num_lines == 0) {
            // `array` now is `char*[1]`
            *lines = (char**)malloc(sizeof(char*)); // A
        }
        else {
            // `array` now is `char*[(*num_lines) + 1]`
            *lines = (char**)realloc(*lines, (*num_lines + 1) * sizeof(char*)); // B
        }

        // *(x+n) is the same as x[n], this line is actually doing:
        // `array[*num_lines] = malloc...
        *(*lines + (*num_lines)) = (char*)malloc((read + 1) * sizeof(char)); // C
        strcpy(*(*lines + (*num_lines)), buffer);
        (*num_lines)++;

        printf("Retrieved line of length %zu:\n", read);
        printf("%s\n", buffer);
    }
    if (buffer) {
        // `line` is `malloc`ed or `realloc`ed by `getline`,
        // have to be `free`ed
        free(buffer);
    }
}
int main(void)
{
    FILE* fp;
    char** array;
    int num_lines;
    fp = fopen("file.txt", "r");
    if (fp == NULL)
        exit(EXIT_FAILURE);
    read_lines(fp, &array, &num_lines);
    printf("After returning\n");
    for (int i = 0; i < *num_lines; i++) {
        printf("%s\n", array[i]);
        free(array[i]); // corresponding to C
    }
    free(array); // corresponding to A or B
    fclose(fp);
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

使用字符串文字傳遞二維字符數組而不在c中初始化

無法通過函數傳遞數組,錯誤:給出字符串

傳遞給 Illuminate\Database\Grammar::parameterize() 的參數 1 必須是數組類型,給定字符串 - 當嘗試通過 eloquent 插入數據庫數據時

無法理解將二維數組傳遞給方法並顯示

通過字典將參數動態傳遞給氣流操作員

SwiftUI 5.5 帶有字符串子字符串的初始化數組?

編輯字符串數組並將其轉換為二維字符數組

用可變長度字符串初始化 fortran 字符數組

如何通過傳遞字符串來獲取對象的值

通過子字符串過濾或減少字符串數組

將字符串數組傳遞給另一個函數

VBA:如何從函數傳遞字符串數組

在 CPP 類的構造函數中初始化二維數組

C 是否通過引用傳遞?

如何通過二維數組索引使用?

將字符串數組傳遞給 VBA 中的 Sheets()

反向自動過濾字符串數組

如果通過引用傳遞,一元和二元運算參數的參數是否保證與原始數據相同?

在 c 中初始化二維數組時出現分段錯誤

如何在 C# 中為 Matrix 類初始化二維數組

如何使用 dplyr 過濾函數將數據庫查詢傳遞給字符串

如何在 mongodb 聚合中將動態字符串傳遞給 $regex

將二維數組傳遞給 c 中的函數時出錯

無法將二維數組傳遞給 C++ 中的函數

在字符串數組和二維數組字符串之間使用 strcmp

為什麼通過 props 正確傳遞的數組返回 undefined?

如何創建一個大小通過文本框傳遞的數組?

將二維字節數組傳遞給 Rust 中的 C

如何讀入字符串並傳輸到數組?