簡體   English   中英

將 malloc 用於字符串數組

[英]Using malloc for an array of strings

我想創建一個名為 arguments 的字符串數組,它從名為 word 的字符串數組中復制條目(從 words[1] 到結尾)。 我在使用 malloc 時遇到問題,我真的不明白 malloc 應該多少錢。 我首先將要存儲的所有字符加起來。 單詞中的最后一個條目始終是 NULL。

words = ["jargon","hello", "world", NULL];
int sum = 0;
for(int i = 1; words[i] != NULL; i++) {
    sum += strlen(words[i]);
}

因此,我將在名為 arguments 的數組中包含總和字符。 所以現在我 malloc 並復制所需的條目。

char **arguments = malloc(sum * sizeof(char));
for(int i = 0; words[i] != NULL; i++) {
    strcpy(arguments[i], words[i+1]);
}

但是,我得到一個 memory 緩沖區溢出。 如果我將其更改為

char **arguments = malloc(sum * sizeof(*arguments));

我通過了 memory 緩沖區溢出,但在下一行的 arguments[i] 中看到了一個未初始化的值。 任何人都可以對發生的事情有所了解嗎?

編輯:對糟糕的風格感到抱歉,並感謝您的建議。

我想創建一個名為 arguments 的字符串數組,它從名為 word 的字符串數組中復制條目

如果是這樣,那么這個循環沒有意義。

int sum = 0;
for(int i = 1; words[i] != NULL; i++) {
    sum += strlen(words[i]);
}

此外 C 中的索引從0開始。 目前尚不清楚為什么循環中的索引i1開始。

您需要分配一個指針數組,然后為指針數組元素指向的字符串分配 memory。

您需要的是以下內容

size_t n = 0;

while ( words[n] != NULL ) ++n;

char **arguments = malloc( n * sizeof( *arguments ) );

for ( size_t i = 0; i != n; i++ )
{
    size_t length = strlen( words[i] );
    arguments[i] = malloc( length + 1 );
    strcpy( arguments[i], words[i] );
}

如果要從復制的字符串集中排除字符串 words[0] ,則代碼片段可能如下所示

size_t n = 0;

while ( words[n+1] != NULL ) ++n;

char **arguments = malloc( n * sizeof( *arguments ) );

for ( size_t i = 0; i != n; i++ )
{
    size_t length = strlen( words[i+1] );
    arguments[i] = malloc( length + 1 );
    strcpy( arguments[i], words[i+1] );
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM