Sathish M Sathish M - 11 months ago 41
C Question

why we can't assign a string value to 2d char array?

int main()
char a[3][5];
int i;


printf("%s \n",a[i]);
return 0;

Why we cant assign string value like this but it can be assigned using string function?

Answer Source

First and foremost, you should check the datatypes for the operands of the assignment operators.

On the LHS, you have a char, and you're trying to assign a char * (RHS) to it. This is type mismatch, hence not possible.

That said, a being a two-dimensional array, you cannot even assign to a[0] either, as arrays (not array elements) are not assignable.

You have to copy the string literal into the memory, however, you have to do something like

 strcpy(a[0], "hai");

So, to answer,

....but it can be assigned using string function?

Well, there's a difference between assignment using assignment operator and copying using the string-family library function. They don't behave the same way. Assignment using assignment operator to an array is not possible, as it needs a modifiable lvalue as the left operand, and an array (name) is not a modifiable lvalue.