2016-02-09 152 views
-4

我的目的是從無符號字符數組複製到無符號字符數組。下面的示例代碼可以解釋從無符號字符複製到無符號字符

#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]; 

請建議如何進行........ ...

+3

我看到'複製* C =新副本;在你的代碼'。請注意,C和C++是不同的語言。 –

+2

你用'd1.d.something [i]'作爲參數調用strncpy,它是一個'char',而不是'char *'。 'strncpy'接受一個指針作爲參數,而不是char。 –

+0

我注意到David,但我想知道另一種方式 –

回答

0

警告和錯誤的原因是strncpy()接受char *參數whi ch不同於unsigned char *

假設在結構兩個數組大小都一樣簡單地做

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

如果您不能承擔兩個數組的大小相同,你需要編寫代碼來檢查和限制根據複製。 memcpy()<string.h>中聲明。

還要注意,運算符new是C++,即使您正在做的其餘部分是香草C,我的答案也是如此。在C中,使用 - 在<stdlib.h>中聲明 - 取而代之。完成後記得釋放內存(使用free())。

1

這個問題是標記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>

參考文獻:

相關問題