user1893063
user1893063

Reputation: 67

How do I concatenate an integer onto a string in C?

The part of the code in question is attempting to decode what register is being used by a MIPS instruction.

This does it by passing in an integer value of the register and then should return a string containing the name of the register. The prince statement that does it is here, where it calls getReg to get the string.

printf("$%d aka $%s\n", itype->rs, getReg(itype->rs));

So far, I've tried this to concatenate them (without the case statements):

char* getReg(int d) {
  char out[4];
  sprintf(out, "a%d", (d - 4));
  return out;
}

But the output results in this:

$6 aka $ìü(

When it should be:

$6 aka $a2

Where am I going wrong with this?

Upvotes: 1

Views: 176

Answers (3)

Grijesh Chauhan
Grijesh Chauhan

Reputation: 58251

You are returning address of a local variable (out).

char* getReg(int d) {
 char out[4];
 sprintf(out, "a%d", (d - 4));
 return out;
}

scope and life of out is within function getReg() only.

Allocate memory dynamically for out to return and access outside function. (and large enough), like below

#define SIZE 25
char* getReg(int d) {
     char *out = malloc(SIZE*sizeof(char));
     sprintf(out, "a%d", (d - 4));   // I don't know about calculation??
      return out;
}

and don't forget to free memory.

Upvotes: 4

alk
alk

Reputation: 70883

As already mentioned by others the OP returns a reference to storage, which is already invalid if used in the call to printf().

An alternative to provide an external buffer whould be this:

char * getReg(int d, char * out) 
{
  sprintf(out, "a%d", (d - 4));

  return out;
}

...

printf(
  "$%d aka $%s\n", 
  itype->rs,  
  getReg(
    itype->rs, 
    (char[32]){0} /* provide a 32 byte long buffer, initialised to 0s */
  )
);

Upvotes: 0

John Bode
John Bode

Reputation: 123458

The array out is local to your getreg function; once the function exits, out no longer exists and the pointer value you return is no longer valid.

It's better to pass the output array as a parameter to the function:

void getReg(int d, char *str)
{
  sprintf(str, "a%d", (d-4));
}

and call it as

char mystr[4];
getReg(r, mystr);

Upvotes: 0

Related Questions