简体   繁体   中英

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). I'm having trouble with malloc and don't really understand how much I should malloc. I first sum all the characters in total that I'm going to be storing. The last entry in words is always 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. So now i malloc and copy the required entries.

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. 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. 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM