How to assign a string value to two dimensional array in C?
I have a sample code, but its not working.
#include<stdio.h>
void main()
{
char f[20][20];
f[0]="abc"; //Error Happens Here
printf("%s",f[0]);
}
How to assign a string value to two dimensional array in C?
I have a sample code, but its not working.
#include<stdio.h>
void main()
{
char f[20][20];
f[0]="abc"; //Error Happens Here
printf("%s",f[0]);
}
This
f[0]="abc";
is wrong as f[0]
is char array and by doing f[0]="abc";
you are trying to change base address of array f[0]
which is not possible. you can understand this simply by considering example of one dimensional char array like
char arr[10] = "hello";
here arr
means base address of array & one can't change that as its constant pointer. And now if you do
arr = "bye"
here you are trying to point arr
to some other address(bye
address) rather than earlier base address.
Correct way is
strcpy(f[0],"abc");
And its better to use strncpy()
instead of strcpy()
as pointed by @Eric here.
You could try this.
void main()
{
char f[20][20] = {0};
sprintf(f[0], "abc"); // or strcpy(f[0], "abc"); but I prefer sprintf
printf("%s",f[0]);
}
Actually, any beginner's book in C
should have told you that arrays (especially strings) are dealt with differently from simple variables such as int
, double
, etc...
So.... Happy reading!