如何在c中输出一个大结构到另一个模块?



对于不应该更改的大结构的输出函数参数是否有最佳实践?返回指针结构或返回整个结构?

的例子:我在文件a中有一个大数据结构,我将从文件B中调用:(typepedef struct在header中). h

typedef struct 
{
int x1;
int x2;
int x3;
int x4;
...
} myStruct;

c

static myStruct data = {...};
errorType myfunction1(mystruct *outData)
{
*outData = data; //copy data to output
...
}
errorType myfunction2(mystruct **outData)
{
*outData = &data; //just return pointer to structure
...
}

myfunction1复制整个结构,所以如果我多次调用这个函数,堆栈大小会增加,处理时间也会增加,但优点是原始数据不能像myfunction2那样在这个文件之外被更改。

两者中有最佳实践吗?

我将对myfunction2中的参数使用const关键字,以便

案例1:编译时,如果调用者使用的结构体的参数也是一个const结构体,那么该结构体的任何变化都肯定会产生error;

案例2:如果调用方的实参不是const,则至少是warning


案例1:

foo。

#ifndef FOO_H
#define FOO_H
typedef struct fooStruct
{
int a;
int b;
int c;
}t_fooStruct;
void cpy_foo(const t_fooStruct ** structToCpy);

#endif

foo.c

#include <stdio.h>
#include <stdlib.h>
#include "foo.h"
t_fooStruct myData = {0,1,2};
void cpy_foo(const t_fooStruct ** structToCpy){
*structToCpy = &myData;
}

c

#include <stdio.h>
#include <stdlib.h>
#include "foo.h"
int main(){
const t_fooStruct * mainData;
cpy_foo(&mainData);
printf("After cpy print %d %d %dn", mainData->a, mainData->b, mainData->c);
mainData->a = 10;
mainData->b = 20;
mainData->c = 30;
printf("After changes print %d %d %dnn", mainData->a, mainData->b, mainData->c);
return 0;
}

编译后得到:

main.c: In function 'main':
main.c:12:15: error: assignment of member 'a' in read-only object
12 |   mainData->a = 10;
|               ^
main.c:13:15: error: assignment of member 'b' in read-only object
13 |   mainData->b = 20;
|               ^
main.c:14:15: error: assignment of member 'c' in read-only object
14 |   mainData->c = 30;
|

案例2:

如果结构体在main中不是const:Main.c(没有const的版本)

int main(){
t_fooStruct * mainData;
cpy_foo(&mainData);
[...]

编译时输出:

9 |   cpy_foo(&mainData);
|           ^~~~~~~~~
|           |
|           t_fooStruct ** {aka struct fooStruct **}
In file included from main.c:3:
foo.h:12:35: note: expected 'const t_fooStruct **' {aka 'const struct fooStruct **'} but argument is of type 't_fooStruct **' {aka 'struct fooStruct **'}
12 | void cpy_foo(const t_fooStruct ** structToCpy);

最新更新