如何将char*复制到16字节数组?代码报错求助
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
SKstring has 16 visible characters, but in memory, it's stored with an extra null terminator (\0). Thememcpywill copy the first 16 bytes (the 16 characters, not the null terminator) sincesizeof(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*touint8_t*is safe here because both are 8-bit types. If you were working with signedcharvalues 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

