C-通过指针动态复制到UINT8_T数组中



如果一个函数将我的指针返回到一个动态/未知大小的UINT8_T数组,我该如何使用该指针填充本地阵列?

uint8_t * func(void){
uint8_t bs[] = {0x34, 0x89, 0xa5}; //size is variant
return bs;
}
void main(void){
uint8_t * p;
static uint8_t myArr[10]; //size is always greater than what's expected from p
p = func();
}

我如何使用 p 填充 myarr ,哪些在不同的呼叫中可能不同?这是否可以确定数组的大小, p 指向?

请原谅我对编程的很少的经验!谢谢。

虽然大多数其他答案和评论都解决了OP示例代码中未定义的行为。我试图回答"将指针复制到动态/未知大小的UINT8_T数组,以及OP如何使用该指针填充本地数组"

  1. 您需要明确传递动态内存的大小/长度: uint8_t *func(size_t *size)如Rowan G的答案所指出的

  2. 或,您需要具有一个哨兵值以在内存中标记数据的末端,例如字符串在C中使用的" 0"来标记字符串的末端。在这种情况下,您将能够通过穿越整个内存(无论何处需要该内存的大小/长度)来计算大小。

{0x34, 0x89, 0xa5, 0x00}; // size depends on the position of 0x00 and ofcourse bound by memory allocated

你不能像想要的那样做。

阵列大小需要已知以用memcpy()复制它,并且您无法在其范围之外返回任何自动变量。离开功能后,功能中的数组就消失了。您要么必须将其分配给malloc()和朋友,要么使其静态。

#include <stdio.h>
#include <stdlib.h>
#include <inttypes.h>
#include <string.h>
uint8_t *func(size_t *size) {
    uint8_t local_bs[] = {0x34, 0x89, 0xa5}; //size is variant
    uint8_t *bs;
    *size = sizeof(local_bs);
    bs = malloc(sizeof(uint8_t) * (*size));
    if (bs == NULL) {
        // allocation error return or exit here.
    }
    memcpy(bs, local_bs, sizeof(uint8_t) * (*size));
    return bs;
}
int main(){
    uint8_t *p;
    size_t *size = malloc(sizeof(size_t));
    if (size == NULL) {
        // allocation error return or exit here.
    }
    size_t i;
    p = func(size);
    // do stuff here with p
    for (i = 0; i < *size; i++) { 
        printf("%"PRIx8"n", p[i]);
    }
    // need to cleanup the manually allocated p
    free(p);
}

最新更新