简体   繁体   中英

How to create an array of strings based on a variable in C

Im trying to create an array of strings based on a variable like the following.

char* stringArray[3];
for(int i = 0; i < 3; i++) {
   sprintf(stringArray[i], "string%d", i);
}

which would create the following array ["string0", "string1", "string2"]. However, it seems this isn't valid and gives me a memory error. What is the right way to accomplish this in C?

You have created the pointers but no storage for the content.

Either char

stringArray[3][100]; // 99 chars +1 null

or

for(int i = 0; i < 3; i++) {

   stringArray[i]=malloc(100); // create memory

   sprintf(stringArray[i], "string%d", i);
}

You've allocated memory for three pointers, but you haven't allocated memory to store each string. Each stringArray[i] needs to point to a buffer large enough to store the final string. That doesn't happen automatically in C, you have to make sure you've allocated memory to store the string itself.

For something like this, where you already know the number of strings and the maximum length of each string, you just need to allocate a 2D array of char :

char stringArray[3][8]; // "string" plus 1 digit plus string terminator

for ( int i = 0; i < 3; i++ )
  sprintf( stringArray[i], "string%d", i );

For a situation where you won't know the length of each string beforehand, you'll want to allocate the array of pointers like you do now, and then do a separate dynamic allocation when you know the length of each string:

char *stringArray[3];

for ( int i = 0; i < 3; i++ )
{
  stringArray[i] = malloc( length_of_this_string() ); 
  if ( stringArray[i] )
    strcpy( stringArray[i], this_string );
}

In C, you need to allocate the space for the string.

char* stringArray[3]; does not give pointers to dynamically sized strings. It gives an array of string pointers that point to nowhere. Use malloc() to allocate your arrays. This answer is close to what you are asking, and it explains allocating space for strings.

You need to allocate space, and you want to make sure you allocate the correct amount of space. Note that the accepted answer is vulnerable to overflow as soon as your string lengths exceed the pre-determined value of 100. It's not that hard to compute things dynamically, and is best practice to avoid statically size buffers (most of the time). For example:

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

void *
xmalloc(size_t s)
{
        void *rv = malloc(s);
        if( rv == NULL ) {
                perror("malloc");
                exit(EXIT_FAILURE);
        }
        return rv;
}

int
main(void)
{
        char* stringArray[3];
        for( int i = 0; i < 3; i++ ) {
                char b;
                int len = snprintf(&b, 1, "string%d", i) + 1;
                stringArray[i] = xmalloc(len * sizeof *stringArray[i]);
                snprintf(stringArray[i], len, "string%d", i);
        }
        for( int i = 0; i < 3; i++ ) {
                printf( "%s\n", stringArray[i]);
        }
        return 0;
}

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