【问题标题】:Const unsigned char* to char*const unsigned char* 到 char*
【发布时间】:2011-02-04 07:39:30
【问题描述】:

所以,我目前有两种类型:

const unsigned char* unencrypted_data_char;
string unencrypted_data;

我正在尝试执行一个简单的数据从一个到另一个的转换(字符串 -> const unsigned char*)

因此,我有以下内容:

strcpy((unencrypted_data_char),(unencrypted_data.c_str()));

但是,我收到错误消息:

error C2664: 'strcpy' : cannot convert parameter 1 from 'const unsigned char *' to 'char *'

有什么建议吗?我认为使用 reinterpret_cast 会有所帮助,但似乎没有什么不同。

【问题讨论】:

    标签: c++ string types char


    【解决方案1】:

    您不能写入 const char *,因为指向的每个 char 都是 const

    strcpy 写入到第一个参数。因此出现错误。

    如果您打算写入 unencrypted_data_char ,请不要将其设为常量(并确保已为其分配了足够的空间!)

    并注意 strcpy 的局限性。确保您提前知道缓冲区需要多大,因为 strcpy 不会停止,直到它足够大 :)

    【讨论】:

    • 不幸的是,让它保持不变不是我的选择。我传递 unencrypted_data 的 AES 加密函数的参数要求它采用“const unsigned char”的形式,因此是我的问题。
    • BSchlinker,这不是问题。 unsigned char* 可以隐式转换为 const unsigned char*
    • 不,不——如果一个函数接受void f(const char *) 之类的东西,它只是说it 不会写入它!它不会阻止你给它一个可变缓冲区。
    • 就像 Alex 说的:避免使用 strcpy!也许使用 strncpy 是一种选择。并且:如果您为 AES 函数使用可变缓冲区,然后 strcpy 将其内容复制到另一个可变缓冲区。为什么不直接把后者交给AES函数呢?
    【解决方案2】:

    好吧,如果unencrypted_data_char指向一个只可读的内存,你最好不要在上面写任何数据,这肯定会导致段错误。

    例如:

        const char *a="abc";
    

    a 指向只读存储器

    如果 unencrypted_data_char 是 const 只是因为你让它成为(比如 const char* a=b),那么你可以使用 const_cast(a) 来转换它。

    如果从 const char* 转换为 unsigned char*。

    1.你需要从 const char* 转换为 char*。使用 const_cast。

    2.从 char* 转换为 unsigned char*。使用 reinterpret_cast。

    【讨论】:

      猜你喜欢
      • 2010-10-22
      • 1970-01-01
      • 1970-01-01
      • 2023-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-23
      相关资源
      最近更新 更多