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.

3
  • What if you use c[20][70] and then do strcpy(&c[k][0], "undefined");? Commented Aug 31, 2011 at 0: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. Commented Aug 31, 2011 at 0:35
  • The universal question: How does it not work? Commented Aug 31, 2011 at 0:39

2 Answers 2

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

1 Comment

I think maybe he wants an array of strings, and to be able to copy into any string in the array.
4

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

Comments

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.