简体   繁体   English

指向结构的参数,函数中引用的成员产生奇怪的值

[英]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: 因此,我想在这里要求别人和我在一起的利益:

  • Why does this occur? 为什么会发生这种情况?
  • Is my syntax the issue here? 我的语法在这里吗?
  • How do I use a pointer to a structure as a parameter for some function, then reference the given structure's members in the scope of the function? 如何使用指向结构的指针作为某些函数的参数,然后在函数范围内引用给定结构的成员? (I'd like to use h_count for t_some_struct as 0) (我想将t_some_struct的h_count设置为0)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM