Using strcpy with a string array in C

Adam picture Adam · Aug 31, 2011 · Viewed 42.7k times · Source

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.

Answer

Seth Carnegie picture Seth Carnegie · Aug 31, 2011

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