在 C 中创建字符串

Creating string in C

我正在尝试在 Texas Instrument CCS 中创建这样的 C 字符串:{steps: nSteps} 以便将其作为 json 发送,nStepsint 。我也想使用以下代码转换为字符串:

    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);

}

我在

中有这个错误
s1[]="{steps:";

s3[]="}"; 

我收到一个错误

"#29 expected an expression"

还有

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

首先,你不能assign c 中的数组。所以,

s1[]="{steps:";

错了。您需要使用 strcpy() 将元素 复制到 数组中。

同样的情况适用于 s3[]="}";s2 = strcat(.. 种陈述。

也就是说,itoa() 不是标准的 C 函数,您应该使用 sprintf() 来实现相同的功能。

一个简单的两行看起来像

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

然后,buf 将具有所需格式的值 as

s1[]="{steps:";

您不能将数组更改为其他地址,因此这行代码没有任何意义。您可能希望 strcpy (s1, "{steps:"); 将该字符串复制到数组中。

s3[]="}";

同样的问题。您不能将数组设置为等于字符串的地址。数组没有可以设置为任何值的单一值。您可能希望 strcpy (s3, "}"); 将该字符串复制到数组中。

s2 = strcat(s1, x);

您正试图在此处更改 s2 本身。我不确定你在这里打算做什么,但这不可能。也许你想要 strcpy(s2, s1); strcat(s2, x);?如果是这样,我想你会 运行 超出 space 因为你只为 s2 分配了 10 个字符。

stepstr = strcat(s2, s3);

设置即将超出范围的变量的值有什么意义?

你真的只需要学习C,没有别的办法。