首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C 語言動態分配字串陣列:二級指標 malloc 兩階段配置與釋放完整流程

     編輯:關於C語言

C 語言動態分配字串陣列:二級指標 malloc 兩階段配置與釋放完整流程

兩階段配置

  1. 配置指標陣列:char **p = malloc(n * sizeof(char*));
  2. 為每字串配置:p[i] = malloc(len * sizeof(char));

完整程式碼

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

char **alloc_strings(int n, int max_len) {
    char **p = malloc(n * sizeof(char*));
    if (!p) return NULL;
    for (int i=0; i

釋放順序鐵律

// 正確
for (i=0; i

進階:單次配置優化

若字串最大長度固定,可一次配置大塊:char *buf = malloc(n * max_len); char **p = malloc(n*sizeof(char*)); for(i) p[i]=buf+i*max_len; 釋放時只需 free(buf); free(p); 兩次呼叫,減少碎片與系統呼叫。

應用場景

  • 讀取未知行數的文字檔。
  • 命令列參數解析 (argv 本質即 char**)。
  • 動態字串集合 (如單字字典)。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved