Reputation: 851
I have two variables as stated below. How do I copy the contents of "varOrig" to "varDest" (no loops for
ou while
)?
const char* varDest = "";
char varOrig[34] = "12345";
Upvotes: 3
Views: 5895
Reputation: 635
memcpy
is the fastest library routine for memory-to-memory copy. It is usually more efficient than strcpy
, which must scan the data it copies or memmove
, which must take precautions to handle overlapping inputs.
// Defined in header <string.h>
void* memcpy( void *dest, const void *src, size_t count );
This code.
#include<string.h>
#include<stdlib.h>
...
char varOrig[34] = "12345";
// calculate length of the original string
int length = strlen(varOrig);
// allocate heap memory, length + 1 includes null terminate character
char* varDest = (char*)malloc((length+1) * sizeof(char));
// memcpy, perform copy, length + 1 includes null terminate character
memcpy(varDest, varOrig, length+1);
Upvotes: 2
Reputation: 15584
If you want to copy the address of the array to the pointer, do this:
varDest = varOrig;
Otherwise, you will need to allocate memory and copy the string.
strdup
is useful for this:
varDest = strdup(varOrig);
You need to free varDest
after using this.
Upvotes: 2