原谅我的C新手!我试图创建一个接受两个char数组作为参数的函数,并返回一些JSON。这是我的代码,然后是编译警告。该程序在执行时会简单地发生段错误。从C函数返回字符串接受两个字符串
#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);
^
你忘了''函数的返回类型。 – xinaiz
您可以使用sprintf()简化所有这些功能 – nosbor
看起来像一个错字。 'char get_json(char * sid,char * obuf)'应该是'char * get_json(char * sid,char * obuf)'。注意返回类型的'*'。 – NathanOliver