You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将char*复制到16字节数组?代码报错求助

Fixing the memcpy Error When Copying a String to a 16-Byte AES Key Array

Let's break down why you're seeing that error and how to fix it quickly.

The root problem is how you're casting the string pointer. Your sample_aes_gcm_128bit_key_t is a typedef for a uint8_t[16] array type—not a pointer type. When you try to cast SK to (sample_aes_gcm_128bit_key_t*), the C compiler doesn't recognize that as a valid conversion, hence the confusing "expected constructor, destructor, or type conversion" error.

The Fixed Code

Instead of casting to the array type, cast the string to a pointer that matches the array's element type (const uint8_t*). Also, remember that the array name alice automatically acts as a pointer to its first element, so no extra casting is needed for the destination.

#include <string.h>
#include <stdint.h>
#include <stdio.h> // For optional debugging output

typedef uint8_t sample_aes_gcm_128bit_key_t[16];

int main() {
    const char *SK = "1234456789999978"; // 16 visible characters (string includes a hidden null terminator)
    sample_aes_gcm_128bit_key_t alice;

    // Correct casting: match the element type of the destination array
    memcpy(alice, (const uint8_t*)SK, sizeof(alice));

    // Optional: Print the key to verify the copy worked
    for (int i = 0; i < sizeof(alice); i++) {
        printf("%02x ", alice[i]);
    }
    printf("\n");

    return 0;
}

Quick Notes to Keep in Mind

  • String Length: Your SK string has 16 visible characters, but in memory, it's stored with an extra null terminator (\0). The memcpy will copy the first 16 bytes (the 16 characters, not the null terminator) since sizeof(alice) is exactly 16. If you need the null terminator included, you'd need a longer string—but AES-128 keys are usually 16 bytes of arbitrary data, not null-terminated strings.
  • Type Safety: Casting char* to uint8_t* is safe here because both are 8-bit types. If you were working with signed char values over 127, you'd need to be careful about sign extension, but since your string uses standard ASCII characters (0-127), this isn't a problem here.

内容的提问来源于stack exchange,提问作者Kumar Roshan Mehta

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:48:57