C 将结构文字作为函数参数传递时出现问题
请看一下这个节目C 将结构文字作为函数参数传递时出现问题,c,C,请看一下这个节目 #include<stdio.h> #include<string.h> typedef struct hs_ims_msrp_authority { int host_type; char buf[50]; int port; }hs_i; int main() { char dom[50]; int i = 10, j = 20; strcpy(dom, "ine"); fun((hs_i){i,
#include<stdio.h>
#include<string.h>
typedef struct hs_ims_msrp_authority
{
int host_type;
char buf[50];
int port;
}hs_i;
int main()
{
char dom[50];
int i = 10, j = 20;
strcpy(dom, "ine");
fun((hs_i){i, dom, j}); // doesnt work
fun((hs_i){i, "dom", j}); // this works
}
int fun(hs_i c)
{
printf("%d %s %d\n", c.host_type, c.buf, c.port);
}
#包括
#包括
类型定义结构hs_ims_msrp_权限
{
int主机类型;
char-buf[50];
国际港口;
}卫生及食物局局长;;
int main()
{
char-dom[50];
int i=10,j=20;
strcpy(dom,“ine”);
乐趣((hs_i){i,dom,j})//不起作用
乐趣((hs_i){i,“dom”,j})//这很有效
}
int fun(hs_i c)
{
printf(“%d%s%d\n”,c.host\u类型,c.buf,c.port);
}
在调用中,以乐趣功能为主;为什么传递字符串文字(“dom”)时函数调用有效,而传递数组变量(dom)时函数调用无效
要使变量工作,是否应以特定的方式进行类型转换?或者还有其他方法吗?在这种情况下
fun((hs_i){i, dom, j});
您只是将指针传递给字符串。
换言之,你只是通过了考试
和“ine”[0]
首先,您需要向前声明您的函数:
fun(hs_i c)
fun(int host_type, char *buf, int port);
....
fun(10, "ine", 20);
.....
int fun(int host_type, char *buf, int port)
{
printf("%d %s %d\n", host_type, buf, port);
}
其次,需要为结构创建存储,因此需要某种类型的临时变量
hs_i temp = { i, NULL, j };
strcpy(temp.buf, "ine")
fun(temp);
或作为单个变量传递给函数:
fun(hs_i c)
fun(int host_type, char *buf, int port);
....
fun(10, "ine", 20);
.....
int fun(int host_type, char *buf, int port)
{
printf("%d %s %d\n", host_type, buf, port);
}
复合文字的存在会分散注意力,错误的原因是试图用另一个
char[]
数组初始化char[]
。以下是非法的:
char dom[50] = "test";
char dom1[50] = dom; /* Line 16, the cause of the error. */
和clang报告以下错误:
main.c:16:10:错误:数组初始值设定项必须是初始值设定项列表或字符串文字
第6.7.8节C99标准初始化第14点规定:
字符类型的数组可以由字符串文字初始化,也可以用大括号括起来。字符串文字的连续字符(如果有空间或数组大小未知,则包括终止的空字符)初始化数组的元素
因此,允许使用字符串literal“dom”
进行调用,因为使用字符串literal初始化数组是合法的,但是不允许使用char[]
进行调用
可能的解决办法:
- 将
的类型更改为buf
const char*
- 将
成员包装在buf
中,这样可以复制它。例如:struct
struct char_array { char data[50]; }; typedef struct hs_ims_msrp_authority { int host_type; struct char_array buf; int port; } hs_i; struct char_array dom = { "ine" }; int i = 10, j = 20; fun((hs_i){i, dom, j}); fun((hs_i){i, { "dom" }, j}); /* Note ^ ^ */
- @Sibrajas:这样做
fun((hs_i){i,*dom,j})
只会复制dom中的第一个字符,而不会复制整个字符串。@prasunheri我没有给出这个(fun((hs_i){i,*dom,j})作为答案。我刚刚解释了为什么fun((hs_i){i,dom,j})不起作用。