Search code examples
carraysfunctionpointersreturn-type

How to return *uint8_t (array) from function of external c file to main.c


I want to find a error free way of returning an uint8_t *hex pointer from function .I have 3 file main.c, function.c , header.h.

main.c:

 uint8_t *hex;
 my_ftn(a,b,c,d,&hex);

function.h

void my_ftn(int a,int b,int c,int d,uint8_t *hex);

function.c

void my_ftn(int a,int b,int c,int d,uint8_t *hex){
   ...
   ...
   a=64;
   hex=malloc(a);  //let a= 64;
   for(i=0;i<a;i++)
     hex[i]= some values;
}

I want to return values hex[i] ,(i=0 to a) to main.c.

Note: return type of my_ftn(function) must be void.


Solution

  • If the variable hex is declared in main like

    uint8_t *hex = NULL;
    

    then declare the function the following way

    void my_ftn(int a,int b,int c,int d,uint8_t **hex){
                                        ^^^^^^^^^^^^^
       ...
       ...
       a=64;
       *hex=malloc(a);  //let a= 64;
       for(i=0;i<a;i++)
         ( *hex )[i]= some values;
    }
    

    that is pass the pointer by reference.

    And call it as you already wrote

    my_ftn(a,b,c,d,&hex);