2015-05-02 38 views
0

如果函数返回一个指向动态/未知大小的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指向?

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

+2

不,事实并非如此。在你的例子中,'func'返回一个指向本地数组的指针。只要func返回,该阵列就不复存在。所以'p'主要指向内存,你根本没有权利使用。 – Mat

+0

返回'bs'in'func'导致UB,不要这样做 – user3528438

+0

是的,这也是一个问题,[这里是关于它的过去的问题](http://stackoverflow.com/questions/4570366/pointer- to-local-variable) – Diego

回答

0

你不能像你想要的那样做。

需要知道数组大小需要与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); 

} 
+0

调用'func'时你缺少一个参数。 –

+0

是固定的。我没有真正测试代码,所以如果我有另一个像这样的错误请纠正我。 –

+0

请在发布之前对您的代码进行一些最低限度的测试(以及一般的答案)。这就是在这里正确回答问题的想法。 –

0

虽然大多数其他答案和评论已经解决了OP的示例代码中未定义的行为。我试图回答“复制指针动态/未知大小的uint8_t阵列,以及如何可以在OP使用指针填补本地阵列”

  1. 你需要明确传递的大小/长度动态内存像这样: uint8_t *func(size_t *size)由罗文G公司的答复中指出

  2. 或者,你需要有一个哨兵值,以纪念在内存中数据的结束,类似于C使用字符串“\ 0”,以纪念字符串的结尾。在这种情况下,只要需要内存的大小/长度,就可以遍历整个内存来计算大小。

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

+1

...或“标记”可能是一个* lead *值,类似于一个Pascal字符串,因此避免了长度扫描操作。或者,由于长度和数据紧密相关,因此可以通过嵌入动态指针和大小成员的值返回一个'struct'。有多种选择。 – WhozCraig

+0

@WhozCraig是的,也是。再加上一个。 – askmish