Reputation: 23
I am trying to manipulate the elements in a 2D array
#include <stdio.h>
main()
{
char arr[][30] = {"hello", "goodbye"};
printf("%s\t%s\n",arr[0], arr[1]);
arr[0] = arr[1];
printf("%s\t%s\n",arr[0], arr[1]);
}
incompatible types when assigning to type ‘char[30]’ from type ‘char *’
I am new to C and coming from an OO background, so my knowledge of pointers is still very fundamental.
I understand this can be done using an array of pointers, but would like to know how to perform this operation with 2D arrays
Thank you for any clarification
Upvotes: 2
Views: 763
Reputation: 210352
You need char* arr[]
instead, since you can't assign an array to another array.
Well, what would that mean? Should it copy over the elements? Use strncpy
or memcpy
for that. Or should it somehow "redirect" the previous array? That doesn't make sense, because an array is just a block of memory... what can you do with it, other than modify its contents? Not much! You can, however, have a pointer to the block, and change it to point somewhere else instead.
No!! Why would they have two different names, then? :P Arrays can decay to pointers implicitly (the address of their first elements), but they're not the same thing! Pointers are just addresses, whereas arrays are a block of data. They have no relation to each other, other than the implicit conversion. :)
Upvotes: 5