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
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. :)
arr[0]
is, itself, an array. C does not support assigning to arrays. If you mean to copy the contents of array arr[1]
into the the array arr[0]
, use memcpy :
memcpy(&arr[0][0], &arr[1][0], sizeof arr[0]);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.