简体   繁体   中英

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";

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.

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);

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM