Reputation: 23
On the code below,
char strArr[5][20];
int i;
for(i=0; i<5; i++)
{
printf("string %d: ", i+1);
gets(strArr[i]);
}
strArr[0]=strArr[1]; //have an compile error on this line. Why cannot assign?
As commented on the last line of code block above, why has a compile error (incompatible type)? Both left and right operands are char* type?
Upvotes: 0
Views: 5888
Reputation: 2534
You are trying to change the base address of the char array strArray[0] with that of strArray[1], which is not permitted. Hence you are getting the error.
Upvotes: 1
Reputation: 30266
char Array[n][m]
: In almost all language, it means : array of array. So, Array[0]
Array[1]
.... is an array. In fact, it is a pointer point to continuous memory of each elements.
And type of this array is : char[m]
. And, when you write : arrayX = arrayY
, you want copy all values in arrayY to arrayX, but C doesn't allow this. You must copy by hand :
for(int i=0; i<=sizeof(arrayX)/sizeof(char); i++)
arrayX[i] = arrayY[i];
I often use memcpy
, but the background is base on the code above.
memcpy (strArray[1],strArray[0],sizeof(strArr[0]));
But, if you declare like this, no compile-error :
char * strArray[5][10]
;
because, it just copy value of pointer : mean copy where this pointer point to. But of course, It changes your code very much. I just draw here for more clearer.
Hope this help :)
Upvotes: 2
Reputation: 36497
Both the left and right operands are of the type char[20]
, not char*
. The variables actually have storage reserved for them, they aren't simply pointers to strings. So the assignment, if it were legal, would be copying 20 characters from one array to the other.
C doesn't let you copy arrays with an assignment operator. Use strcpy
, strncpy
, or memcpy
instead.
(I suspect the specific wording of the error is because an array decays into a pointer in some places, and I expect the left side of an assignment is not one of those places, while being used on the right side of an assignment is.)
Upvotes: 4