I have built a function that gets an integer argument and returns a char array.
For example, for an argument of 13 the function should return "0013"; for an argument of 3 the function should return "0003".
But I don't get an error and I cannot show this value with printf(getInstructionIndex(13));
Here is my code:
/* get Instruction Index how "0001" or "0010" */
char * getInstructionIndex(int index){
char number1;
char number2;
char number3;
char *str = (char *) malloc(sizeof(char) * 4);
if(index < 10){
number1 = '0';
number2 = '0';
number3 = '0';
str[0] = number1;
str[1] = number2;
str[2] = number3;
str[3] = index;
return str;
}
else{
if(index < 100 && index >= 10){
number1 = '0';
number2 = '0';
str[0] = number1;
str[1] = number2;
str[2] = index;
return str;
}
else
{
if(index < 1000 && index >= 100){
number1 = '0';
str[0] = '0';
str[1] = index;
return str;
}
else
{
str[0] = index;
return str;
}
}
}
free(str);
}
Here is my main:
int main(int argc, char *argv[]){
printf("started\n");
printf(getInstructionIndex(13)); /* i must see 0013*/
printf("stopped\n");
return 0;
}