[英]Pointer to a struct as a parameter, members referenced within function produce strange values
I'm tasked with adding the quick-fit allocation algorithm to MINIX, and as such need to use structures a lot. 我的任务是向MINIX添加快速匹配分配算法,因此需要大量使用结构。 However, I came accross something for which I cannot find any resources on a solution.
但是,我遇到了一些我无法在解决方案上找到任何资源的东西。
The below code is a quick example I made to demonstrate the issue I have met with. 下面的代码是我用来说明遇到的问题的快速示例。
#include <stdlib.h>
#include <stdio.h>
struct some_struct {
int h_count;
};
void why();
struct some_struct * myStruct;
int main(){
myStruct = (struct some_struct *) malloc(sizeof(struct some_struct));
myStruct->h_count=0;
printf("%d\n", myStruct->h_count);
why(&myStruct);
return 0;
}
void why(struct some_struct * t_some_struct){
printf("%d\n", t_some_struct->h_count);
}
The output of the printf in the function why is different from the output given in main. 函数Why中的printf输出与main中给出的输出不同。 The value printed by why is a seemingly random number that changes every time the program is ran.
由Why打印的值是一个看似随机的数字,每次运行程序时都会改变。
Output: 输出:
0
7870280
Press any key to continue . . .`
The 7870280 changes on every run. 7870280每次运行都会更改。 I would assume it is printing some kind of memory value or something, but that's just a guess as I have no idea really.
我会假设它正在打印某种内存值或某些东西,但这只是一个猜测,因为我真的不知道。
As such, I thought I'd ask here for the benefit of others alongside myself: 因此,我想在这里要求别人和我在一起的利益:
Thanks 谢谢
The function why
expects a pointer whereas you are passing a pointer to pointer. 该函数
why
在您将指针传递给指针时期望指针。 Call as why(myStruct);
调用为
why(myStruct);
(by the way, myStruct
is a global variable, so passing is a bit superfluous here). (顺便说一句,
myStruct
是一个全局变量,因此在这里传递有点多余)。 Rest of your accessing the struct member is fine. 其余访问struct成员的操作都很好。
Not directly related but some general suggestions: 没有直接关系,但有一些一般建议:
1) Use standard prototype for main()
such as int main(int argc, char*argv[])
1)对
main()
)使用标准原型,例如int main(int argc, char*argv[])
2) Casting the result of malloc is needless and error-prone. 2)强制转换malloc的结果是不必要的,并且容易出错。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.