简体   繁体   English

将 malloc 用于字符串数组

[英]Using malloc for an array of strings

I want to create an array of strings called arguments that copies entries from an array of strings called words (from words[1] until the end).我想创建一个名为 arguments 的字符串数组,它从名为 word 的字符串数组中复制条目(从 words[1] 到结尾)。 I'm having trouble with malloc and don't really understand how much I should malloc.我在使用 malloc 时遇到问题,我真的不明白 malloc 应该多少钱。 I first sum all the characters in total that I'm going to be storing.我首先将要存储的所有字符加起来。 The last entry in words is always NULL.单词中的最后一个条目始终是 NULL。

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

So i will have sum characters in my array called arguments.因此,我将在名为 arguments 的数组中包含总和字符。 So now i malloc and copy the required entries.所以现在我 malloc 并复制所需的条目。

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

However, i get a memory buffer overflow.但是,我得到一个 memory 缓冲区溢出。 If i change it to如果我将其更改为

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

I get past the memory buffer overflow but instead am greeted with an uninitialized value in arguments[i] in the next line.我通过了 memory 缓冲区溢出,但在下一行的 arguments[i] 中看到了一个未初始化的值。 Could anyone shed some light on what's going on?任何人都可以对发生的事情有所了解吗?

Edit: Sorry about the poor style and thanks for the advice.编辑:对糟糕的风格感到抱歉,并感谢您的建议。

I want to create an array of strings called arguments that copies entries from an array of strings called words我想创建一个名为 arguments 的字符串数组,它从名为 word 的字符串数组中复制条目

If so then this loop does not make sense.如果是这样,那么这个循环没有意义。

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

Moreover indices in C start from 0 .此外 C 中的索引从0开始。 It is unclear why the index i in you loop starts from 1 .目前尚不清楚为什么循环中的索引i1开始。

You need to allocate an array of pointers and then allocate memory for strings that will be pointed to by elements of the array of pointers.您需要分配一个指针数组,然后为指针数组元素指向的字符串分配 memory。

What you need is the following您需要的是以下内容

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] );
}

If you want to exclude the string words[0] from the set of copied strings then the code snippet can look like如果要从复制的字符串集中排除字符串 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