如何在C中复制char数组? [英] How to copy a char array in C?

查看:1000
本文介绍了如何在C中复制char数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C语言中,我有两个char数组:

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

如何将array1的值复制到array2?我可以这样做吗?array2 = array1?

解决方案

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

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

话虽这么说,建议的字符串方式是使用 strncpy .它可以防止导致例如缓冲区溢出的常见错误(如果由用户输入(键盘,网络等)填充.像这样:

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

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

In C, I have two char arrays:

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

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

解决方案

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

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.

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 array1 is filled from user input: keyboard, network, etc). Like so:

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

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

这篇关于如何在C中复制char数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆