wBB
wBB

Reputation: 851

How to copy char array to char pointer in C?

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

Answers (2)

khanh
khanh

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

S.S. Anne
S.S. Anne

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

Related Questions