C语言 如何在C中复制字符数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16645583/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 06:23:58  来源:igfitidea点击:

How to copy a char array in C?

carrayscharcopy

提问by user2131316

In C, I have two char arrays:

在 C 中,我有两个字符数组:

char array1[18] = "abcdefg";
char array2[18];

How to copy the value of array1to array2? Can I just do this: array2 = array1?

如何复制的价值array1array2?我可以这样做array2 = array1吗:?

回答by aymericbeaumet

You can't directly do array2 = array1, because in this case you manipulate the addresses of the arrays (char *) and not of their inner values (char).

您不能直接执行array2 = array1,因为在这种情况下,您操作的是数组 ( char *)的地址,而不是其内部值 ( char) 的地址。

What you, conceptually, want is to do is iterate through all the chars of your source (array1) and copy them to the destination (array2). There are several ways to do this. For example you could write a simple for loop, or use memcpy.

从概念上讲,您想要做的是遍历源 ( array1) 的所有字符并将它们复制到目标 ( array2)。有几种方法可以做到这一点。例如,您可以编写一个简单的 for 循环,或使用memcpy.

That being said, the recommended way for strings is to use strncpy. It prevents common errors resulting in, for example, buffer overflows(which is especially dangerous if array1is filled from user input: keyboard, network, etc). Like so:

话虽如此,推荐的字符串方法是使用strncpy. 它可以防止常见错误导致,例如,缓冲区溢出(如果array1从用户输入填充,则特别危险:键盘、网络等)。像这样:

// Will copy 18 characters from array1 to array2
strncpy(array2, array1, 18);

As @Prof. Falken mentioned in a comment, strncpycan be evil. Make sure your target buffer is big enough to contain the source buffer (including the \0at the end of the string).

作为@Prof。Falken 在评论中提到,strncpy可以是邪恶的。确保您的目标缓冲区足够大以包含源缓冲区(包括\0字符串末尾的 )。

回答by kAmol

If your arrays are not string arrays, use: memcpy(array2, array1, sizeof(array2));

如果您的数组不是字符串数组,请使用: memcpy(array2, array1, sizeof(array2));

回答by Prof. Falken contract breached

If you want to guard against non-terminated strings, which can cause all sorts of problems, copy your string like this:

如果您想防止可能导致各种问题的未终止字符串,请像这样复制您的字符串:

char array1[18] = {"abcdefg"};
char array2[18];

size_t destination_size = sizeof (array2);

strncpy(array2, array1, destination_size);
array2[destination_size - 1] = '
snprintf(array2, destination_size, "%s", array1);
';

That last line is actually important, because strncpy()does not always null terminatestrings. (If the destination buffer is too small to contain the whole source string, sntrcpy() will not null terminate the destination string.)

最后一行实际上很重要,因为strncpy()并不总是null 终止字符串。(如果目标缓冲区太小而无法包含整个源字符串,则 sntrcpy() 不会空终止目标字符串。)

The manpage for strncpy() even states "Warning: If there is no null byte among the first n bytes of src, the string placed in dest will not be null-terminated."

strncpy() 的联机帮助页甚至指出“警告:如果 src 的前 n 个字节中没有空字节,则放置在 dest 中的字符串不会以空值结尾。”

The reason strncpy() behaves this somewhat odd way, is because it was not actually originally intended as a safe way to copy strings.

strncpy() 表现出这种有点奇怪的方式的原因是因为它实际上最初并不是作为复制字符串的安全方式。

Another way is to use snprintf() as a safe replacement for strcpy():

另一种方法是使用 snprintf() 作为 strcpy() 的安全替代品:

strcpy(array2, array1);

(Thanks jxhfor the tip.)

(感谢jxh的提示。)

回答by unwind

You cannot assign arrays, the names are constants that cannot be changed.

您不能分配数组,名称是无法更改的常量。

You can copy the contents, with:

您可以复制内容,使用:

typedef struct { char a[18]; } array;
array array1 = { "abcdefg" };
array array2;

array2 = array1;

assuming the source is a valid string and that the destination is large enough, as in your example.

假设源是有效字符串并且目标足够大,如您的示例所示。

回答by jxh

As others have noted, strings are copied with strcpy()or its variants. In certain cases, you could use snprintf()as well.

正如其他人所指出的,字符串strcpy()与其变体一起被复制。在某些情况下,您也可以使用snprintf()

You can only assign arrays the way you want as part of a structure assignment:

作为结构分配的一部分,您只能以您想要的方式分配数组:

void foo (char x[10], char y[10]) {
    x = y;    /* pointer assignment! */
    puts(x);
}

If your arrays are passed to a function, it will appear that you are allowed to assign them, but this is just an accident of the semantics. In C, an array will decay to a pointer type with the value of the address of the first member of the array, and this pointer is what gets passed. So, your array parameter in your function is really just a pointer. The assignment is just a pointer assignment:

如果你的数组被传递给一个函数,看起来你被允许分配它们,但这只是语义的一个意外。在 C 中,数组将衰减为具有数组第一个成员地址值的指针类型,并且传递的是该指针。因此,函数中的数组参数实际上只是一个指针。赋值只是一个指针赋值:

char array1[18] = "abcdefg";
char array2[18];
array2 = array1; /* fails because array1 becomes a pointer type,
                    but array2 is still an array type */

The array itself remains unchanged after returning from the function.

从函数返回后,数组本身保持不变。

This "decay to pointer value" semantic for arrays is the reason that the assignment doesn't work. The l-value has the array type, but the r-value is the decayed pointer type, so the assignment is between incompatible types.

数组的这种“衰减到指针值”语义是赋值不起作用的原因。左值具有数组类型,但右值是衰减的指针类型,因此分配是在不兼容的类型之间进行的。

void cstringcpy(char *src, char * dest)
{
    while (*src) {
        *(dest++) = *(src++);
    }
    *dest = '
#include <iostream>
#include <fstream>
#include <cstring>
#define TRUE 1
#define FALSE 0
typedef int Bool;
using namespace std;
Bool PalTrueFalse(char str[]);
int main(void)
{
char string[1000], ch;
int i = 0;
cout<<"Enter a message: ";

while((ch = getchar()) != '\n') //grab users input string untill 
{                               //Enter is pressed
    if (!isspace(ch) && !ispunct(ch)) //Cstring functions checking for
    {                                //spaces and punctuations of all kinds
        string[i] = tolower(ch); 
        i++;
    }
}
string[i] = '
array2 = array1;
'; //hitting null deliminator once users input cout<<"Your string: "<<string<<endl; if(PalTrueFalse(string)) //the string[i] user input is passed after //being cleaned into the null function. cout<<"is a "<<"Palindrome\n"<<endl; else cout<<"Not a palindrome\n"<<endl; return 0; } Bool PalTrueFalse(char str[]) { int left = 0; int right = strlen(str)-1; while (left<right) { if(str[left] != str[right]) //comparing most outer values of string return FALSE; //to inner values. left++; right--; } return TRUE; }
'; } ..... char src[6] = "Hello"; char dest[6]; cstringcpy(src, dest);

As to why the "decay to pointer value" semantic was introduced, this was to achieve a source code compatibility with the predecessor of C. You can read The Development of the C Languagefor details.

至于为什么引入“decay to pointer value”语义,这是为了实现与C的前身的源代码兼容,详见C语言的发展

回答by Boris

it should look like this:

它应该是这样的:

#include <string.h>    

int array1[10] = {0,1,2,3,4,5,6,7,8,9};
int array2[10];


memcpy(array2,array1,sizeof(array1)); // memcpy("destination","source","size")

回答by akhil

I recommend to use memcpy() for copying data. Also if we assign a buffer to another as array2 = array1, both array have same memory and any change in the arrary1 deflects in array2 too. But we use memcpy, both buffer have different array. I recommend memcpy() because strcpy and related function do not copy NULL character.

我建议使用 memcpy() 来复制数据。此外,如果我们将一个缓冲区分配给另一个 as array2 = array1,则两个数组都具有相同的内存,并且 arrary1 中的任何更改也会在 array2 中偏转。但是我们使用 memcpy,两个缓冲区都有不同的数组。我推荐 memcpy() 因为 strcpy 和相关函数不复制 NULL 字符。

回答by geneemailbox1 geneemailbox1

c functions below only ... c++ you have to do char array then use a string copy then user the string tokenizor functions... c++ made it a-lot harder to do anythng

c 函数仅低于... c++ 你必须做字符数组然后使用字符串副本然后使用字符串标记器函数... c++ 使得做任何事情都变得更加困难

##代码##

回答by MOHAMED

##代码##

is not supported in c. You have to use functions like strcpy()to do it.

在 c 中不支持。您必须使用strcpy() 之类的函数来执行此操作。

回答by D0rm1nd0

for integer types

对于整数类型

##代码##