6

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.

Adam
  • 61
  • 1
  • 1
  • 2
  • What if you use `c[20][70]` and then do `strcpy(&c[k][0], "undefined");`? – aroth Aug 31 '11 at 00:31
  • 1
    Sorry, but "I actually know it's an array of character arrays, I need it like that" just doesn't make any sense. If you want to copy a string somewhere, that "somewhere" has to be a character array. Not an array of character arrays, but a character array. You don't get to "need it like that" in this case. – AnT stands with Russia Aug 31 '11 at 00:35
  • The universal question: How does it not work? – Keith Thompson Aug 31 '11 at 00:39

2 Answers2

9

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");
Seth Carnegie
  • 73,875
  • 22
  • 181
  • 249
  • 1
    I think maybe he wants an array of strings, and to be able to copy into any string in the array. – aroth Aug 31 '11 at 00:30
3

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]);
Miguel Grinberg
  • 65,299
  • 14
  • 133
  • 152