1

我想创建一个称为参数的字符串数组,它从称为单词的字符串数组中复制条目(从单词 [1] 到结尾)。我在使用 malloc 时遇到了麻烦,我真的不明白我应该使用多少 malloc。我首先将要存储的所有字符加起来。words 中的最后一个条目始终为 NULL。

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

所以我将在我的数组中有总和字符,称为参数。所以现在我 malloc 并复制所需的条目。

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

但是,我得到内存缓冲区溢出。如果我将其更改为

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

我越过了内存缓冲区溢出,而是在下一行的 arguments[i] 中看到一个未初始化的值。任何人都可以对发生的事情有所了解吗?

编辑:对糟糕的风格感到抱歉,并感谢您的建议。

4

1 回答 1

1

I want to create an array of strings called arguments that copies entries from an array of strings called words

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. It is unclear why the index i in you loop starts from 1.

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.

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

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] );
}
于 2019-11-20T09:59:17.370 回答