0

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]

Bida Bamk
  • 3
  • 1
  • 1
    You are declaring chx as an array of 12 pointers to char. Types need to match how they are used. – stark Jan 01 '23 at 14:35
  • 1
    And after you fix the type, read this: [**How to access a local variable from a different function using pointers?**](https://stackoverflow.com/questions/4570366/how-to-access-a-local-variable-from-a-different-function-using-pointers) – Andrew Henle Jan 01 '23 at 14:37

1 Answers1

1
  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;    
}
0___________
  • 60,014
  • 4
  • 34
  • 74