1

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?

0

4 Answers 4

1

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);
}
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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.

Comments

1

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

2 Comments

Are you sure about that sizeof? Should it be sizeof *stringArray[i] or just sizeof(char)? Otherwise you are allocating memory for a number of character pointers equal to the length of the string plus 1.
@JustinOtto You are correct. Fortunately, we do want sizeof(char) (or just 1), so the mistake is in our favor. I was trying to demonstrate the x = xmalloc(n * sizeof *x) idiom and failed horribly. I will edit.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.