【发布时间】:2018-12-18 06:45:56
【问题描述】:
我尝试使用伪代码来尝试专注于问题并删除任何无关的内容。我在头文件中有一个结构的定义:
struct.h
typedef struct {
int value;
} structname;
static structname struct_array[NUMBER];
start.c
#include "struct.h"
static void functionA() {
function1 (&struct_array[index]);
}
Setup.c
#include "struct.h"
int function1(structname * name) {
int result = 0;
name->value = 2;
printf("The value before function2: d", result->value);
result = function2(name);
printf("The resulting value: d", result->value);
printf("The address of the member to be modified is: %p", &(name->value));
return result;
}
Modification.c
#include "struct.h"
int function2(structname * name) {
int result = 0;
name->value = 1;
printf("The resulting value: d", name->value);
printf("The address of the member to be modified is: %p", &(name->value));
return result;
}
这会返回:
The value before function2: 2
The resulting value: 1
The address of the member to be modified is: 12345
The resulting value: 2
The address of the member to be modified is: 12345
事情是这样的:地址是一样的。函数如何看起来正在修改结构的成员,但在函数返回时,结构成员保留其原始值?
我应该使用extern 关键字吗?如何以及在哪里?
编辑: 我想我会做一些测试,看看我是否能找到问题所在。我所做的只是迷惑自己。所以事实证明,如果我向结构添加第二个成员,比如 int nextValue,修改会在该结构上运行并返回,我可以对其进行测试,并且它会被修改。那么它怎么能对一个成员而不是另一个成员起作用呢?我很困惑。关于测试什么的任何想法?
【问题讨论】:
-
static structname struct_array[NUMBER];您是否知道每个包含struct.h的C 文件(翻译单元)都有自己的struct_array副本?如果将static替换为extern会发生什么变化? -
您提供的这段代码无法编译,
int result = 0;后跟`printf("The value before function2: d", result->value);`无效.请提供正确的minimal reproducible example。 -
只是猜测,因为您没有提供代码...您将其放在头文件中:
static structname struct_array[NUMBER];。每个翻译单元都有自己的数组副本。您可以考虑将数组放在单个 C 文件中,然后在标头中将数组声明为extern,以便程序中的目标文件使用一个数组。
标签: c function pointers struct member