Adam
Adam

Reputation: 61

Using strcpy with a string array in C

I have a character array defined as follows: char *c[20];
I'm trying to do: strcpy(c[k], "undefined); but it's not working

I've also tried defining it as char c[20][70] with no luck.

Edit: I actually know it's an array of character arrays, I need it like that.

Upvotes: 6

Views: 55853

Answers (2)

Seth Carnegie
Seth Carnegie

Reputation: 75130

That's not a character array; that's an array of character pointers. Remove the * to make it a character array:

char c[20];

Then you can use strcpy:

strcpy(c, "undefined");

If you really did want an array of character arrays, you'll have to do what you said you tried:

// array that holds 20 arrays that can hold up to 70 chars each
char c[20][70];

// copy "undefined" into the third element
strcpy(c[2], "undefined");

The problem could have been you're missing the closing ", I don't know if that was a paste error though. Or, the problem could have been that you're using k without defining it, we can't know without seeing the error message you get.

If you want to set them all to that string, then just loop over them:

char c[20][70];

int i;
for (i = 0; i < 20; ++i)
    strcpy(c[i], "undefined");

Upvotes: 9

Miguel Grinberg
Miguel Grinberg

Reputation: 67479

If what you want is to have 20 strings of 70 chars each then your second option should work:

char c[20][70];
for (int k = 0; k < 20; k++)
    strcpy(c[k], "undefined");

The char *c[20] definition is incorrect because you are just defining an array of 20 pointers, and the pointers are not initialized. You could make it work in this way:

char *c[20];
for (int k = 0; k < 20; k++) {
    c[k] = malloc(70);
    strcpy(c[k], "undefined");
}

// then when you are done with these strings
for (int k = 0; k < 20; k++)
    free(c[k]);

Upvotes: 4

Related Questions