Amit Rege
Amit Rege

Reputation: 37

In a 2D array a[row][column] what does a[row] stand for?

I want to add a string to a char 2D array.

#include<stdio.h>
#include<string.h>
int main(void)
{
   char a[20][20]={"fire","ice","water"};
   a[3]="land";
   printf("%s",a[3]);
}

I get and error message saying

incompatible types when assigning to type ‘char[20]’ from type ‘char *’
a[3]="land"; 

     ^

The code works if instead I use strcpy(a[3],"land").
So my question is why doesn't the first code work?Isn't a[3] a pointer to the first element of the fourth row of the char array? If it is not a pointer,then why does strcpy() work even though it expects a pointer argument?
I'm a beginner and this is my first question on SO so I apologize for any mistakes.

Upvotes: 1

Views: 89

Answers (3)

Gopi
Gopi

Reputation: 19864

Arrays are not assignable in C. Yes array decays to a pointer while using strcpy() and a[3] will point to the 4th row of your 2D array.

Whereas in the case a[3] = "land" a[3] doesn't decay to a pointer.

For ex:

char *p;
p = "hello";

This is a valid assignment because p is a pointer.Whereas

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

Since a is a array and not a pointer you will get an error for this. Note the difference between an array and a pointer.

Upvotes: 2

Tiekeo
Tiekeo

Reputation: 63

You cannot add directly a string to a char **. This is a feature usually supported by the OOP (Oriented Object Programming) languages.

"a[3]="land";" is not supported by C, you need to use a fonction that will assign each character to each char of your char *. The main one is strcpy() (man strcpy).

Upvotes: 0

Spikatrix
Spikatrix

Reputation: 20244

Arrays are not assignable. You must assign individual characters one by one which is what strcpy does.

The type of a[i] is char[20] ,i.e, an array of characters of size 20 and the type of "land" is char* , a pointer to char. These are not compatible types and this is what the compiler is complaining about.

Upvotes: 4

Related Questions