从未签名字符复制到无符号字符
copy from unsigned char to unsigned char
我的目的是从无符号字符数组复制到无符号字符数组。下面的示例代码可以解释
#include <stdio.h>
#include <string.h>
typedef struct _demo
{
unsigned char something[6];
}demo;
typedef struct _Demo
{
demo d;
}Demo;
typedef struct _copy
{
unsigned char do_something[6];
}copy;
int main()
{
copy *c = new copy;
Demo d1;
for(int i = 0; i < 6; i++)
{
c->do_something[i] = i;
printf("%u", c->do_something[i]);
strncpy(d1.d.something[i], c->do_something[i], sizeof(d1.d.something));
}
return 0;
}
我得到的输出是:
In function 'int main()':
28:33: error: invalid conversion from 'unsigned char' to 'char*' [-fpermissive]
In file included from 2:0:
/usr/include/string.h:132:14: note: initializing argument 1 of 'char* strncpy(char*, const char*, size_t)'
extern char *strncpy (char *__restrict __dest,
^
28:53: error: invalid conversion from 'unsigned char' to 'const char*' [-fpermissive]
In file included from 2:0:
/usr/include/string.h:132:14: note: initializing argument 2 of 'char* strncpy(char*, const char*, size_t)'
extern char *strncpy (char *__restrict __dest,
我想避免:
d1.d.something[i] = c->do_something[i];
请建议如何进行...
这个问题
被标记为C++
,并且您使用了new
(C++操作),所以我假设您想了解C++,而不是C,对吗?
// make sure the memory gets released when the
// pointer goes out of scope
// (requires #include <memory>)
std::unique_ptr< copy > c( new copy );
// fills the elements of c->do_something with
// sequentially increasing values, starting with 0
// (requires #include <numeric>)
std::iota( std::begin( c->do_something ), std::end( c->do_something ), 0 );
// copies from c->do_something to d1.d.something
// (requires #include <algorithm>)
std::copy( std::begin( c->do_something ), std::end( c->do_something ), std::begin( d1.d.something ) );
使用 std::begin()
和 std::end()
(允许像容器一样处理数组)需要 #include <iterator>
。
引用:
- unique_ptr
- 约塔
- 复制
警告和错误的原因是strncpy()
接受char *
参数,这与unsigned char *
不同。
假设结构中的两个数组大小相同,只需
memcpy(d1.d.something, c->do_something, sizeof(d1.d.something));
如果不能假设两个数组的大小相同,则需要编写代码来检查并限制复制。 memcpy()
在<string.h>
中声明。
另请注意,运算符new
是C++,即使您正在执行的其余部分是香草 C,我的答案也是如此。 在 C 中,改用 malloc()
- 在 <stdlib.h>
中声明 - 代替。 并记得完成后释放内存(使用free()
)。
相关文章:
- 在这种情况下,我真的复制了字节还是复制了字符?
- 如何返回/复制unique_ptr<无符号字符[]>的值?
- 使用动态分配将 char* 复制到另一个字符**
- 库达如何将字符**从内核复制到主机
- 将字符向量复制到另一个向量
- 如何将一个结构的字符数组复制到结构的另一个字符数组中?
- 将字符数组复制到 QByte 数组中,而无需传递指针
- 为什么我的代码在尝试复制字符数组时引发 C6386 错误?
- 使用 strcpy_s 将字符串复制到字符*
- 字符* 复制到另一个字符* 运行时错误
- C 内联汇编试图将STD :: String的字符复制到寄存器中
- 如何将 (ICU4C) Unicode 字符串逐个字符复制到另一个 Unicode 字符串
- 将第一个n个字符复制到std :: string
- 将无符号字符*复制到无符号字符
- 如何在 C++ 中将一些字符复制到字符串中
- 从未签名字符复制到无符号字符
- 您好,我想将一个字符复制到 2D 数组,但第二个字符会擦除第一个字符
- 将分配有 malloc 的字符 * 复制到 std::string
- 如何在c++中进行反向字符复制
- 如何将字符复制到字符数组