c - 如何在 C 中将 char 指针转换为 uint8_t 数组?

标签 c

我需要将字符串 (char*) 转换为 __uint8_t 数组。我知道后者是 unsigned char 的别名,但我不知道如何正确转换它。

示例:

char *ssid = "XXXXX";

这是必要的,因为我必须调用一个仅接受 __uint8_t 数组而不接受 char* 数组的 API。

struct WifiConfig {
    uint8_t ssid[32];
    uint8_t password[64];
};

struct WifiConfig wifi_config;
wifi_config.ssid = ???

如果我尝试转换:

wifi_config.ssid = (__uint8_t *) ssid;

我收到以下错误:

error: assignment to expression with array type
     wifi_config.ssid = (__uint8_t *) ssid;

抱歉,如果这是个愚蠢的问题,上次我玩 C 时我还是个青少年。

提前致谢!

最佳答案

刚刚转换:

const char *name = "My Full Name";
yourAPIFunction((__uint8_t *) name);

注意:这违反了常量正确性。您必须确保yourAPIFunction不会改变name。如果是这样,那么您需要将其memcpy(以及free!)到局部变量中,并提供给它,这样它的突变就不会影响池化的变量。 -“我的全名”的任何其他用户使用的字符串。

对您的(完全不同的)更新问题的回复:

这些数组的存储是内联的,它们不像典型的 char * 那样指向堆。您需要将字符串的内容复制到其中:

// ssid must be at most 31 chars (plus NUL terminator)
// password must be at most 63 chars (plus NUL terminator)
struct WifiConfig new_wifi_config(char *ssid, char *password) {
    struct WifiConfig wifi_config;
    memcpy(wifi_config.ssid, ssid, strlen(ssid)+1)
    memcpy(wifi_config.password, ssid, strlen(ssid)+1)
    return wifi_config;
}

关于c - 如何在 C 中将 char 指针转换为 uint8_t 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47682797/

相关文章:

c - pthreads C 程序在执行时挂起

c - C程序中的输入

无法编译 : Nested Structures

c - 为什么没有 FVIRTKEY CreateAcceleratorTable() 就不能工作?

python - 如何在c中扩展python?

c - 如果我在 parent 和 child 中 fork 和 exec 会发生什么?

无法将 strcmp 的参数 1 从 char 转换为 const char

c++ - 带有模板的奇怪解析行为 _Atomic

c - TCP/IP Echo 客户端挂起

c - 反转链表的每 k 个节点