-1
#include<stdio.h>
int main() {
    char R_FPD[] = "+00393E33mm/go";
    char R_FPH[] = "+00393E33mm/go";
    char R_Vel[] = "+00393E33mm/go";
    char R_Tot[] = "+00393E33mm/go";
    char str_msg[] = "{"+"flow_rate_per_day"+":"+R_FPD+","+"flow_rate_per_hour"+":"+R_FPH+","+"velocity"+":"+R_Vel+","+"totalizer"+":"+R_Tot+"}";

    printf("%s", str_msg);
  
    return 0;
}

i want to make it like a json object but its not working

Richard Critten
  • 2,138
  • 3
  • 13
  • 16
Noman
  • 594
  • 1
  • 18

1 Answers1

1

Arrays in C decay to pointers to their first elements and adding pointers is not defined in C standard.

The simplest way to concatenate string like this is using sprintf function. It works like printf but it prints into a C-string.

In your case the pattern could be following:

char str_msg[BIG_ENOUGH];
sprintf(str_msg, "{flow_rate_per_day:%s,flow_rate_per_hour:%s,velocity:%s,totalizer:%s}", R_FPD,R_FPH,R_Vel,R_Tot);

BIG_ENOUGH should be larger then the longest string that can be formed. 256 should be enough in your case.

Alternatively you can use asprintf function that will automatically allocated a buffer of the right size. Remember to use free when the buffer is no longer needed.

char *str_msg;
asprintf(&str_msg, "{flow_rate_per_day:%s,flow_rate_per_hour:%s,velocity:%s,totalizer:%s}", R_FPD,R_FPH,R_Vel,R_Tot);
... use str_msg

free(str_msg);
tstanisl
  • 13,520
  • 2
  • 25
  • 40