从unsigned char复制到unsigned char

时间:2016-02-09 12:31:18

标签: c++ string

我的目的是从unsigned char数组复制到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];

请建议如何进行...........

2 个答案:

答案 0 :(得分:1)

这个问题是标记的 C++,你使用new(一个C ++操作),所以我假设你想学习C ++,而不是C,对吗? / p>

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

参考文献:

答案 1 :(得分:0)

警告和错误的原因是strncpy()接受char *个参数,这与unsigned char *不同。

假设结构中的两个数组大小相同,只需执行

 memcpy(d1.d.something, c->do_something, sizeof(d1.d.something));

如果您不能假设这两个数组的大小相同,那么您需要编写代码来检查并限制复制。 memcpy()中声明了<string.h>

另请注意,运算符new是C ++,即使你正在做的其余部分是vanilla C,我的答案也是如此。在C中,使用malloc()中声明的<stdlib.h>代替。并且记得在完成后释放内存(使用free())。