Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

string literal in c

Tags:

c

Why is the following code illegal?

typedef struct{
   char a[6];
} point;

int main()
{
   point p;
   p.a = "onetwo";
}

Does it have anything to do with the size of the literal? or is it just illegal to assign a string literal to a char array after it's declared?

like image 694
ossau Avatar asked Aug 13 '10 03:08

ossau


1 Answers

It doesn't have anything to do with the size. You cannot assign a string literal to a char array after its been created - you can use it only at the time of definition.

When you do

char a[] = "something";

it creates an array of enough size (including the terminating null) and copies the string to the array. It is not a good practice to specify the array size when you initialize it with a string literal - you might not account for the null character.

When you do

char a[10];
a = "something";

you're trying to assign to the address of the array, which is illegal.

EDIT: as mentioned in other answers, you can do a strcpy/strncpy, but make sure that the array is initialized with the required length.

strcpy(p.a, "12345");//give space for the \0
like image 176
Amarghosh Avatar answered Oct 04 '22 02:10

Amarghosh