简体   繁体   English

如何将char数组复制到C中的char指针?

[英]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 )? 如何复制“varOrig”到“varDest”(无环路的内容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: strdup对此很有用:

varDest = strdup(varOrig);

You need to free varDest after using this. 使用后需要释放varDest

memcpy is the fastest library routine for memory-to-memory copy. memcpy是内存到内存复制的最快库例程。 It is usually more efficient than strcpy , which must scan the data it copies or memmove , which must take precautions to handle overlapping inputs. 它通常比strcpy更有效, strcpy必须扫描它复制或memmove的数据,这必须采取预防措施来处理重叠输入。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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