How to combine two integers into one string using C?

–3 votes
asked Jun 12, 2017 by kayan

I have two integers and I want to combine them into one string in the following way: for example, given xx=555, yy=3, I want the string to be: "555-03". The value in yy resembles hours in my case, so it has to contain two digits, but days it doesn't matter and there is a difference between "555-03" and "555-3". Any ideas how I can do something like this?

this basicly i get the following error :function returns address of local variable [-Wreturn-local-addr] My try:

#include <stdio.h>
#include <stdlib.h>
#include <stdlib.h>

static char* intToTimeDate(int day,int hour);
int main()
{
    int hour=5555;
    int curr_day=7;

    char* curr_time=intToTimeDate(curr_day,hour);
    printf("dd=%s",curr_time);
    return 0;
}


static char* intToTimeDate(int day,int hour){
          char str[16];
           snprintf ( str, sizeof ( str) - 1, "%d-%02d", day,hour);
           printf("str=%s",str);
           return str;
        }

1 Answer

0 votes
answered Jun 13, 2017 by chux

OP's code works except that it returns a pointer to a local variable which is UB once the function ends. Instead pass a pointer to valid memory to store the result.

static char* intToTimeDate(char *str, int day,int hour){
   sprintf(str, "%d-%02d", day, hour);
   printf("str=%s",str);
   return str;
}

The destination string should be wide enough to accommodate any pair of int values.

A solution to return a pointer to a string involves allocating the string. With C99 onward, code can use a compound literal for temporary space. The pointer returned from intToTimeDate() is valid until the end of the block - the lifetime of the compound literal.

#include <limits.h>
#include <stdio.h>

static char* intToTimeDate(char *str, int day, int hour) {
  sprintf(str, "%d-%02d", day, hour);
  return str;
}

// Size needed to store a decimal string verison of `int`
#define INT_DEC_SIZE (sizeof(int)*CHAR_BIT/3 + 3)
//                         v--- compound literal ----------------------v
#define INTTOTIMEDATE(d,y) (intToTimeDate((char [INT_DEC_SIZE*2 + 2]){0}, (d), (y)))

int main(void) {
  puts(INTTOTIMEDATE(555, 3));  // Output "555-03\n"
  return 0;
}
Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
Website Online Counter

...