Use*_*ynn -2 c scope sdl pass-by-reference sdl-2
以下链接表示中定义的结构main没有函数调用的范围,因为它们是本地的,因此您应该全局定义结构。但是对于变量,最好在本地声明变量并通过指针传递给函数,而不是声明全局变量。
在纯 C 中有没有办法使用指针等将 main 中定义的结构传递给函数?如果您不介意,请使用示例程序来演示该方法。谢谢。
在哪里声明结构,在 main() 内部还是在 main() 外部?
这段代码有效,但不是我想要的。我想在main. 这可能吗?
#include <stdio.h>
#include <SDL2/SDL.h>
void function();
struct hexColour
{
Uint32 red;
}hc;
int main(void)
{
hc.red = 0xFFFF0000;
function(hc);
return 0;
}
void function(struct hexColour hc)
{
printf("red is %x\n", hc.red);
}
Run Code Online (Sandbox Code Playgroud)
我想要的是:
int main(void)
{
struct hexColour
{
Uint32 red;
}hc;
hc.red = 0xFFFF0000;
function(hc);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
首先,您应该真正使用与函数定义匹配的正确原型。
其次,您的示例确实将结构传递给hc函数中的局部变量。
在function运行时,内存中有两种不同且独立的结构:一种在main函数中,一种在function函数中。
为了涵盖我的基础,这里有两个可能被问到的另外两个问题的答案:
您想在main函数内部定义结构本身,然后才能在其他函数中使用它。
就像是
int main(void)
{
struct hexColor
{
uint32_t white;
// Other members omitted
};
struct hexColour hc;
hc.white = 0xff;
func(hc); // Assume declaration exist
}
void func(struct hexColour my_colour)
{
printf("White is %u\n", my_colour.white);
}
Run Code Online (Sandbox Code Playgroud)
这是不是可能的。该结构仅hexColour在main函数内部定义。没有其他函数可以使用该结构。不管你是否传递一个指针,结构hexColour仍然只存在于main函数内部。
通过将指针传递给结构对象来模拟传递引用。喜欢
struct hexColor
{
uint32_t white;
// Other members omitted
};
int main(void)
{
struct hexColour hc;
hc.white = 0xff;
// Assume declaration of function exists
func(&hc); // Emulate pass-by-reference by passing a pointer to a variable
}
void func(struct hexColour *colourPointer)
{
colourPointer->white = 0x00;
}
Run Code Online (Sandbox Code Playgroud)
这是可能的,因为结构hexColour存在于main函数之外,在全局范围内。在结构定义之后声明和定义的所有函数都可以使用该结构及其成员。
| 归档时间: |
|
| 查看次数: |
1687 次 |
| 最近记录: |