Originally Posted by
thone
If I would like to copy array like this:
suppose I got and array of char, i.e. char buffer[50]. The want to copy them by reference to char* mydata.
"copy <...> by reference" has no meaning.
If you do that, you just assign a value to a variable. The value is the address of the buffer array, and the variable is a pointer to char. It's now pointing to 'buffer' (actually, buffer + 0).
but then if I change buffer, mydata also change. Is there any way to let the buffer change its address so that I don't have to copy them to another location.
If you want a copy, you need room. No miracle to be expected here!
Statically:
Code:
{
char mydata[sizeof buffer];
memcpy (mydata, buffer, sizeof buffer); /* <string.h> */
}
Dynamically:
Code:
{
char* mydata = malloc (sizeof buffer); /* <stdlib.h> */
if (mydata != NULL)
{
memcpy (mydata, buffer, sizeof buffer);
/* when finished */
free (mydata), mydata = NULL;
}
}