从未签名字符复制到无符号字符

copy from unsigned char to unsigned char

本文关键字:字符 复制 无符号      更新时间:2023-10-16

我的目的是从无符号字符数组复制到无符号字符数组。下面的示例代码可以解释

#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())。