【发布时间】:2022-01-12 20:43:22
【问题描述】:
从现在开始,我已经阅读 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 的访问需要取消引用。
是否可以在不改变我的界面的情况下避免将结构从一个复制到另一个?
提前感谢您的回答! 里斯。
【问题讨论】:
-
我认为混合指针和原始变量是个坏主意。如果您的代码是在 C++ 中,您可以使用引用,但 C 中没有这种机制。因此,如果您想避免复制,则必须使用指针。实际上,在给定的示例中,不需要指针,因为与其他 i/o 操作相比,复制两个
shorts的结构是一个相对较快的操作。但是,如果myType结构有可能变得足够大(以至于复制变得低效),那么指针是使这段代码运行良好的唯一方法。 -
感谢您的回答,我预计 myType 中有 ~5 个变量和 ~20 个实例。复制是可以的,即使在嵌入式系统上也是如此。我只是在寻找最好的方法......
标签: c pointers struct dereference