10

here is a code sample

void something()
{
   char c[100];
   scanf("%s",c);
   char c2[100]=c;
}

my problem is when i do this assignment an error says that i can't assign

char * "c"  to char[] "c2";

how can i achieve this assignment?

5
  • 1
    wait wait.. are you wanting to assign the data inside of c to c2 or are you wanting to assign the pointer c to c2 ?
    – Earlz
    Jan 15, 2010 at 19:20
  • 1
    probably-homework? Do we really need this tag? Why not add but-you-never-know-,-it-may-be-work-as-well? Jan 15, 2010 at 19:21
  • 2
    No, we don't need that tag - tags should NOT be used to express opinions - that's what comments are for.
    – anon
    Jan 15, 2010 at 19:22
  • i am trying to assign the data not pointer Jan 15, 2010 at 19:23
  • BTW, your function needs a name, not just a void return type. Jan 15, 2010 at 21:21

4 Answers 4

19

You'll have to use strcpy() (or similar):

...  
char c2[100];
strcpy(c2, c);

You can't assign arrays using the = operator.

0
6

You need to use strcpy()

char c2[100];
strcpy(c2, c);
4

Better practice would be to use strncpy(c2, c, 100) to avoid buffer overflow, and of course limit the data entry too with something like scanf("%99s", c);

1
  • 4
    What you said is correct, but some general C advice for other readers: 1. Be careful with strncpy since it won't necessarily NUL-terminate. (Not a problem here since both c and c2 have the same number of elements, but OTOH, that also means plain strcpy wouldn't be a problem either.) 2. fgets would be better than scanf. c-faq.com/stdio/scanfprobs.html
    – jamesdlin
    Jan 15, 2010 at 20:17
3

char [] is not a valid value type in C (its only a valid declaration type), so you can't actualy do anything with char [] types. All you can do is convert them to something else (usually char *) and do something with that.

So if you wany to actually do something with the data in the array, you need to use some function or operation that takes a char * and derefences it. Obvious choices for your example are strcpy or memcpy

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.