![](/img/trans.png)
[英]C: Why can you pass (to a function) a struct by value, but not an array?
[英]Can you pass a struct of function arguments to a function?
我正在使用第三方庫(使用我無法編輯的代碼!),該庫具有接受大量參數的功能。 使用它看起來像這樣:
void func(int a, int b, int c, int d, int e) {
//do something...
}
int main(void) {
func(1, 2, 3, 4, 5);
}
但是,它接受了這些論點並立即將其丟棄。 我想堅持這些論點,並將其用於其他方面。 我想要做的是一樣的東西:
void func(int a, int b, int c, int d, int e) {
//do something...
}
typedef struct foo foo;
struct foo {
int a;
int b;
int c;
int d;
int e;
};
foo bar = {1, 2, 3, 4, 5};
int main(void) {
func(bar);
}
不幸的是,這引發了類型錯誤:
main.c:17:8: error: incompatible type for argument 1 of 'func'
func(bar);
^~~
main.c:12:6: note: expected 'int' but argument is of type 'foo {aka struct foo}'
void func(int a, int b, int c, int d, int e) {
^~~~
main.c:17:3: error: too few arguments to function 'func'
func(bar);
^~~~
做func(bar.a, bar.b, bar.c, bar.d, bar.e);
可行,但是羅word。 我可以做些指針魔術來解決這個問題嗎? 同樣,我無法修改庫代碼。
不,沒有辦法做到這一點。 但是,如果您經常調用該函數,則可能值得將該函數包裝在自己的函數中,因此您可以將指向結構的指針作為參數傳遞給函數,然后通過其不太美觀的參數方法調用實際函數。
可能值得一提的是,對於每個傳遞的參數,將一項壓入堆棧,因此,如果函數期望特定數量的參數,則在二進制級別上,則期望將許多參數壓入堆棧。 對於無法控制的功能,您無法更改。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.