gpt4 book ai didi

c - 从接受两个字符串的 C 函数返回字符串

转载 作者:行者123 更新时间:2023-11-30 21:00:50 27 4
gpt4 key购买 nike

原谅我的 C 新手!我正在尝试创建一个接受两个 char 数组作为参数并返回一些 JSON 的函数。这是我的代码,后面是编译警告。该程序在执行时只是出现段错误。

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

char get_json(char *sid, char *obuf)
{
char *json;
json = malloc(strlen(obuf)+37);
strcpy(json, "{\"sessionline\":{\"sid\":\"");
strcat(json, sid);
strcat(json, "\",\"line\":\"");
strcat(json, obuf);
strcat(json, "\"}}");
return json;
}

int main()
{
char *sid = "xyzxyzxyz";
char *obuf = "asdfasdfasdfasdf";
char *json = get_json(sid, obuf);
printf(json);
}

使用 gcc 编译时:

test.c: In function ‘get_json’:
test.c:14:9: warning: return makes integer from pointer without a cast [enabled by default]
return json;
^
test.c: In function ‘main’:
test.c:21:22: warning: initialization makes pointer from integer without a cast [enabled by default]
char *json = get_json(sid, obuf);
^
test.c:22:9: warning: format not a string literal and no format arguments [-Wformat-security]
printf(json);
^

最佳答案

  • get_json 应返回指针 char*,而不是 char
  • 您忘记将 sid 包含在要分配的长度中,因此您的程序将导致超出范围的访问并调用未定义的行为
  • 这个程序没有什么害处,但通常将用户输入的字符串放入 printf() 的格式字符串中是危险的。

试试这个:

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

char get_json(char *sid, char *obuf)
{
char *json;
json = malloc(strlen(sid)+strlen(obuf)+37);
if(json == NULL) return json;
strcpy(json, "{\"sessionline\":{\"sid\":\"");
strcat(json, sid);
strcat(json, "\",\"line\":\"");
strcat(json, obuf);
strcat(json, "\"}}");
return json;
}

int main(void)
{
char *sid = "xyzxyzxyz";
char *obuf = "asdfasdfasdfasdf";
char *json = get_json(sid, obuf);
if (json != NULL) fputs(json, stdout);
}

或者更简单:

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

char get_json(char *sid, char *obuf)
{
char *json;
json = malloc(strlen(sid)+strlen(obuf)+37);
if(json == NULL) return json;
sprintf(json, "{\"sessionline\":{\"sid\":\""
"%s"
"\",\"line\":\""
"%s"
"\"}}", sid, obuf);
return json;
}

int main(void)
{
char *sid = "xyzxyzxyz";
char *obuf = "asdfasdfasdfasdf";
char *json = get_json(sid, obuf);
if(json != NULL) fputs(json, stdout);
}

关于c - 从接受两个字符串的 C 函数返回字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38400548/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com