Creating string in C

158 Views Asked by At

I'm trying to create in Texas Instrument CCS a string in C like this : {steps: nSteps} in order to send it as a json, nSteps is an int .I want to convert into a string as well with the following code:

    void jsonSteps(char* stepstr, int steps)
{
    char x[3];
    const char s1[10], s3[10];
    char s2[10];
    itoa(steps,x,10);
    s1[]="{steps:";

    s3[]="}";
    s2 = strcat(s1, x);
    stepstr = strcat(s2, s3);

}

I have this error in

s1[]="{steps:";

and

s3[]="}"; 

I receive an error

"#29 expected an expression"

and also

" #169-D argument of type "const char *" is incompatible with parameter of type "

2

There are 2 best solutions below

0
On BEST ANSWER
s1[]="{steps:";

You can't change an array to be at some other address, so this line of code doesn't make any sense. You probably want strcpy (s1, "{steps:"); to copy that string into the array.

s3[]="}";

Same problem. You can't set an array equal to the address of a string. Arrays don't have a single value you can set to anything. You probably want strcpy (s3, "}"); to copy that string into the array.

s2 = strcat(s1, x);

You are trying to change s2 itself here. I'm not sure what you're intending here, but that can't possibly work. Maybe you want strcpy(s2, s1); strcat(s2, x);? If so, I think you'll run out of space since you only allocated 10 characters for s2.

stepstr = strcat(s2, s3);

What's the point of setting the value of a variable that's about to go out of scope?

You really just need to learn C, there's no other way to put it.

0
On

First of all, you cannot assign arrays in c. So,

s1[]="{steps:";

is wrong. You need to make use of strcpy() to copy elements into the array.

Same case apply for s3[]="}";, s2 = strcat(.. kind of statements.

That said, itoa() is not a standard C function, you should use sprintf() to achieve the same.

A simple two-liner would look like

 //assuming steps hold the int value
 char buf[128] ={0};
 sprintf(buf, "{steps: %d }", steps);

and then, buf will have the value as in the required format.