[英]Why is the output of this C program 0?
In this code I am trying to pass a pointer to the structure and then use this pointer to work on the structure members, but why is the output always showing 0?在这段代码中,我试图传递一个指向结构的指针,然后使用这个指针来处理结构成员,但为什么输出总是显示 0?
#include<stdio.h>
#include<string.h>
struct student
{
int go;
} s;
void m();
void main()
{
m(&s);
printf("%d",s.go);
}
void m(struct student *ptr)
{
ptr->go;
}
struct student
{
int go;
}s;
creates a global variable.创建一个全局变量。 Global variables are zero initialized unless they are initialized explicitly.
除非显式初始化全局变量,否则它们都是零初始化的。 That statement is equivalent to:
该语句等效于:
struct student
{
int go;
};
struct student s = {0};
Hence the value of s.go
is 0
.因此
s.go
值为0
。 The call to m
does not change the values of any variables.对
m
的调用不会改变任何变量的值。 It has no effect on the output.它对输出没有影响。 The output will be
0
even if the call to m(&s)
is removed.即使删除了对
m(&s)
的调用,输出也将为0
。
The global variable s
is initialized with all members 0
.全局变量
s
被初始化为所有成员0
。
Nothing changes the value of s.go
, so the output is 0
. s.go
的值没有任何变化,因此输出为0
。
'0'
and if char or string than '\\0'
.'0'
并且如果char 或 string大于'\\0'
。 So you are getting Value 0
.0
。struct student { int go; } s;
Your question has all sorts of errors, here they are, in no particular order:你的问题有各种各样的错误,它们在这里,没有特定的顺序:
#include <string.h>
if you aren't using any "string" functions#include <string.h>
s
to functions to access the struct);s
的指针传递给函数来访问结构的需要); you should remove the global variable (ie, make it local) and continue to pass the pointer-to-struct as you are to m()
in order to be able to access it outside of main()
(where you should declare it)m()
以便能够在main()
之外访问它(您应该在那里声明它)main()
is incorrect as I pointed out in a comment to OP, and naturally you are missing the return 0;
main()
签名不正确,自然而然您错过了return 0;
statement in main()
because of this main()
语句因此printf()
printf()
中缺少换行符ptr->go
in m()
;ptr->go
in m()
做任何事情; you aren't assigning anything to it or otherwise using it.static
,) are (default-)initializedstatic
,)是(默认)初始化的Here is an example with corrections (note you can initialize s
as described by others if you wish to use it's value before you modify/set it):这是一个带有更正的示例(请注意,如果您希望在修改/设置之前使用它的值,则可以按照其他人的描述初始化
s
):
#include <stdio.h>
struct student
{
int go;
};
void m();
int main(void)
{
struct student s;
m(&s);
printf("%d\n", s.go);
return 0;
}
void m(struct student *ptr)
{
ptr->go = 5;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.