1

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]);
}
nipoo
  • 170
  • 1
  • 9

2 Answers2

4

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.

Achal
  • 11,821
  • 2
  • 15
  • 37
3

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!

PhoenixBlue
  • 967
  • 2
  • 9
  • 26
  • 2
    Using sprintf() instead of strcpy() is all well and good until your input string contains a %s (or similar), and then your program crashes. (Obviously it doesn’t contain one in this case but if the argument was a macro or variable instead of a string literal, that might not be so obvious anymore). (strncpy() would be even safer) – Jeremy Friesner Oct 24 '18 at 14:27
  • 1
    `sprintf` is also most likely some ~100 times less efficient than `strcpy`. – Lundin Oct 24 '18 at 14:54