简体   繁体   English

在C中传递“直接”结构作为函数

[英]Passing “direct” struct as function in C

I have a simple question about structures in C. 我对C中的结构有一个简单的问题。

I have this struct and this function: 我有这个结构和这个功能:

struct Vec2
{
  int x;
  int y;
}

void draw(Sprite* sprite, struct Vec2 pos);

Is there anyway to do the equivalent in c++? 无论如何在c ++中做相同的操作?

draw(foo, new Vec2(10, 20));

I tried this but the compiler doesn't agree with me: 我试过这个,但编译器不同意我的意见:

draw(foo, {10, 20} );

Anybody to help ? 有人帮忙吗?

Edit: I use Visual C++ 2008 Express in C++ mode, but for my school I must code in straight C, not C++ 编辑:我在C ++模式下使用Visual C ++ 2008 Express,但对于我的学校,我必须使用C语言编写,而不是C ++

If your compiler supports C99 or later, you can use a compound literal : 如果您的编译器支持C99或更高版本,则可以使用复合文字

draw(foo, (struct Vec2){10, 20});

or, if you want to be more explicit about the member names: 或者,如果您想更明确地了解成员名称:

draw(foo, (struct Vec2){.x = 10, .y = 20});

(Note that Microsoft's C compiler doesn't support C99, which could limit the portability of your code.) (请注意,Microsoft的C编译器不支持C99,这可能会限制代码的可移植性。)

What I usually do is : 我通常做的是:

struct Vec2 make_Vec2( int x, int y ) {
  struct Vec2 vec;
  vec.x = x; vec.y = y;
  return vec;
}

...
draw( foo, make_Vec2( 10, 20 ) );

Just adding a working example with @Keith Thompson's answer: 只需添加@Keith Thompson答案的工作示例:

#include <stdio.h>
#include<string.h>
struct two{
 int x;
 int y;
};
draw(struct two t){
    printf("\nx=%d y=%d\n", t.x, t.y);
}
int main(){
 draw((struct two){1,2});
 draw((struct two){.y = 1, .x = 2});
} 

Output: 输出:

:~$ ./a.out 

 x=1 y=2

 x=2 y=1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM