0

I'm using Zephyr RTOS on nRF52832, and I need to convert int (> 10) into char.

I have this function :

char* int2char(int data)
{
   int test[7] = {0};
   char c[7];
   int nbdata = powerTen(data);
   int i, rest = 0;
   for (i=0;i <= nbdata ; i++)
   {
       int pow = power(10,nbdata-i);
       test[i] = data /pow - rest;
       c[i] = '0' + test[i];
       // subtract everything that has been calculated before
       rest = rest*10 + test[i]*10;
   }
   printk("in function : int2char C : %c\n",*c);
   printk("in function : int2char C : %c\n",*(c+1));
   printk("in function : int2char C : %c\n",*(c+2));
   printk("in function : int2char C : %c\n",*(c+3));
   printk("in function : int2char C : %c\n",*(c+4));
   printk("in function : int2char C : %c\n",*(c+5));
   printk("in function : int2char C : %c\n",*(c+6));
   return c;
}

And this in main():

char *c = int2char(987654);
    printk("int2char C : %c\n",*c);
    printk("int2char C : %c\n",*(c+1));
    printk("int2char C : %c\n",*(c+2));
    printk("int2char C : %c\n",*(c+3));
    //...

in Putty, I have: Putty Screen for the printk

printk in function works well but not in main. I have tried several things and searched for hours, nothing works.

anastaciu
  • 23,467
  • 7
  • 28
  • 53
DaMaj
  • 11
  • 1

1 Answers1

2

c is a local variable confined to the scope of the function, its lifetime will expire when the function execution is complete.

Returning a pointer to c and then accessing it, by way of dereference, after the function is executed will invoke undefined behavior.

As an alternative you can allocate memory for c:

char *int2char(int data)
{
    char *c = malloc(7); //#include <stdlib.h>
    //...
    return c;
}

int main()
{        
    char *c = int2char(987654);    
    //use c
    free(c);          
}

In this case the lifetime of c will become the same as the program unless you free the reserved memory (which you should do when your are done using it), so it's safe to return a pointer to it.

You can also use static storage, the variable will have the same lifetime as the program:

static char c[7];

Again, this makes c safe to return from the function, in this case c will live on until the program is finished, it's not possible to free it.

A third alternative is to pass c as an argument of the function:

void int2char(int data, char *c)
{
    //...
    // no return needed
}

int main()
{
    char c[7];
    int2char(987654, c);    
    //...   
}

This is probably the best option, avoiding manual memory allocation and static storage duration, but this is my opinion.

Side note:

Using c[0], c[1], etc. is more readable than using the pointer notation *c, *(c+1), etc.

anastaciu
  • 23,467
  • 7
  • 28
  • 53