Sathish M Sathish M - 2 months ago 6
C Question

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

#include<stdio.h>
int main()
{
char a[3][5];
int i;

a[0][5]="hai";
a[1][5]="cool";
a[2][5]="many";

for(i=0;i<3;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

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.