Home > Net >  extracting a string from a function in C
extracting a string from a function in C

Time:01-02

I having problems extracting chx then ch only returns the first charecter

char* chini(long int a){
    char* chx[12];
    itoa (a,chx,10);
    return *chx;    
    }
char ch[12];

*ch=chini(init);
    
    puts(ch);

I want to have all of chx in ch but it only returns chx[0]

CodePudding user response:

  1. char* chx[12]; is an array of pointers not chars
  2. You return a reference to the local variable which stops to exist when function returns.

Both are undefined behaviours (UBs)

You have three ways of doing it:

char *chini1(int a){
    char *chx = malloc(12);
    itoa(a ,chx, 10);
    return chx;    
}

IMO the best::

char *chini2(char *chx, int a){
    itoa(a,chx,10);
    return chx;    
}

The worst:

char *chini3(int a){
    static char chx[12];
    itoa(a,chx,10);
    return chx;    
}
  • Related