从指针访问 C char 数组

问题描述 投票:0回答:1

我试图通过指针将 C char 数组传递给函数,然后访问函数中的 char 数组。目前我似乎只能访问第一个字符,其余的只是随机字节。我一直在尝试检查函数调用之前和之后的变量,它们在函数调用之前都是正确的。

我认为这个问题有答案,因为它指的是取消引用并仅保留第一个字符,但是当我尝试实现该解决方案时,我仍然得到单个字符而不是整个字符串。

这是我的代码:

#include <stdio.h>
#include <string.h>
#include <stdint.h>

void hex_to_bytes(char *hex, char **bytes, size_t *bytes_len) {
    int length = strlen(hex) % 2 ? strlen(hex) + 1 : strlen(hex);
    unsigned char checkedHex[length];
    
    for (int i = 0; i <= length; i++) {
        if (i == 0 && strlen(hex) % 2){
            checkedHex[0] = '0';
        }
        else if (i == length){
            checkedHex[i] = '\x00';
        }
        else {
            checkedHex[i] = hex[i]; 
        } 
    }
    
    *bytes_len = length / 2;
    int counter = 0;
    for (int i = 0; i < length / 2; i++){
        sscanf(&checkedHex[counter], "%2hhx", &bytes[i]);
        counter += 2;
    }
}

void *b64_encode(unsigned char *bytes, size_t bytes_len)
{
    printf("in b64_encode %p\n", bytes);
    printf("bytes = %s\n", &bytes[48]);

    printf("0x");
    for (int i = 0; i < bytes_len; i++) {
        printf("%02X", bytes[i]);
    }
    printf("\n");
}

int main() {
    unsigned char hex[] = "49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d";
    unsigned char *bytes[48] = {0};
    size_t bytes_len = 0;

    hex_to_bytes(hex, (unsigned char **) &bytes, &bytes_len);

    printf("in main       %p\n", &bytes);
    printf("bytes = %s\n", &bytes[48]);

    unsigned char *base64 = b64_encode(bytes, bytes_len);
    return 1;
}

我得到的输出是:

in main       0x7ff7b0ef1350
bytes = 49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d
in b64_encode 0x7ff7b0ef1350
bytes = l
0x490000000000000027000000000000006D0000000000000020000000000000006B000000000000006900000000000000
c
1个回答
0
投票

unsigned char *bytes[48] 
是指针数组,而不是字符数组。摆脱
*

并且,在

hex_to_bytes()
中,将
char **bytes
更改为
char *bytes
。您不需要指向指针的指针。

© www.soinside.com 2019 - 2024. All rights reserved.