How to convert from char * to char [] in c

here is a sample code

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

my problem is when I do this task, the error says that I cannot assign

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

How can I achieve this mission?

+4
source share
4 answers

You will need to use strcpy() (or the like):

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

You cannot assign arrays with the = operator.

+10
source

You need to use the strcpy () command

 char c2[100]; strcpy(c2, c); 
+6
source

It would be best practice to use strncpy (c2, c, 100) to avoid buffer overflows and, of course, restrict data entry to something like scanf ("% 99s", c);

+4
source

char [] not a valid value type in C (its only a valid declaration type), so you cannot do anything with type char [] . All you can do is convert them into something else (usually char * ) and do something with it.

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

+2
source

All Articles