從現在開始我已經閱讀 Stackoverflow 很長時間了,我學到了很多東西。
但是現在我遇到了一個問題,我在 Stackoverflow 上找不到,即使它應該是一個“標準”問題。所以如果這個話題已經得到回答,請原諒我。
問題:
我正在撰寫一個模塊,其中定義了輸入和輸出結構的介面。它應該是某種“多路復用器”,可能具有三個輸入和一個輸出。模塊應該將輸入之一切換到輸出(取決于某些邏輯)。
這里顯示了一個作業示例:
#include <stdio.h>
typedef struct{
short myVariable1;
short myVariable2;
} myType;
struct input_type{
myType Inp1;
myType Inp2;
myType Inp3;
};
struct output_type{
myType Out1;
};
struct input_type input;
struct output_type output;
void main(){
for (int i=0; i<10; i ){ // this for loop simulates a cyclic call of a function where all the inputs are written
input.Inp1.myVariable1 = i;
input.Inp2.myVariable1 = i*2;
input.Inp3.myVariable1 = i*3;
printf("Inp1: %d | Inp2: %d | Inp3: %d \n",input.Inp1.myVariable1,input.Inp2.myVariable1,input.Inp3.myVariable1);
output.Out1 = input.Inp2; // Actual routing is done here, but i want to avoid this copy by working on the same dataset (e.g. input.InpX)
printf("Out: %d\n",output.Out1.myVariable1);
}
}
在這個剪輯中,結構在每個回圈中都被簡單地復制。為了避免這一步,我可以執行以下操作:
#include <stdio.h>
typedef struct{
short myVariable1;
short myVariable2;
} myType;
struct input_type{
myType Inp1;
myType Inp2;
myType Inp3;
};
struct output_type{
myType * Out1;
};
struct input_type input;
struct output_type output;
void main(){
output.Out1 = &input.Inp2; // Actual routing is done here; But in this case, the output structure includes a pointer, therefore all other modules need to dereference Out1 with "->" or "*"
for (int i=0; i<10; i ){ // this for loop simulates a cyclic call of a function where all the inputs are written
input.Inp1.myVariable1 = i;
input.Inp2.myVariable1 = i*2;
input.Inp3.myVariable1 = i*3;
printf("Inp1: %d | Inp2: %d | Inp3: %d \n",input.Inp1.myVariable1,input.Inp2.myVariable1,input.Inp3.myVariable1);
printf("Out: %d\n",output.Out1->myVariable1);
}
}
但在這種情況下,輸出結構不再與現有介面兼容。對 Out1 的訪問需要取消參考。
Is it possible to avoid copying the structures from one to another without changing my interface?
Thanks in advance for your answers! Rees.
uj5u.com熱心網友回復:
是否可以避免在不更改界面的情況下將結構從一個復制到另一個?
通過“現有介面”,我認為您的意思是您擁有使用這種型別物件的代碼......
struct output_type{ myType Out1; };
...并且您希望避免修改該代碼。
在那種情況下,不,你不能替代
struct output_type{ myType * Out1; };
. 此外,在前一個結構的設計中,填充myType直接成員涉及復制您關心的所有資料,無論是在每個成員的基礎上還是在整個結構的基礎上。
在這一點上,我建議您堅持制作這些副本,直到并且除非您發現這樣做會導致性能或記憶體使用不令人滿意。在這一點上進行更改將不僅僅涉及句法更改:需要仔細審查 的所有用法,struct output_type以查找和減輕代碼依賴原始結構屬性的任何情況(例如對非鋸齒有信心)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/384363.html
