简体   繁体   English

关于C中结构的奇数输出

[英]An odd output about a struct in C

I tried a simple struct. 我尝试了一个简单的结构。

#include<stdio.h>
struct test
{ 
  int i; 
  int j; 
}; 
int main() 
{ 
  struct test t; 
  t.i=1; 
  t.j=2; 
  printf("t:%d, i:%d, j:%d\n", t, t.i, t.j); 
} 

the output is incorrect as: 输出不正确如下:

"t:1, i:2, j:1 "

if I change the printf sentence to 如果我将printf句子更改为

printf("i:%d, j:%d\n", t.i, t.j); 

the output is correct: 输出是正确的:

"i:1, j:2" 

why the first one cannot print the correct output? 为什么第一个无法打印正确的输出? Am I missing something here? 我在这里错过了什么吗? I'm using gcc on ubuntu. 我在ubuntu上使用gcc。 Thanks. 谢谢。

The pattern you give printf() tells it how it should read the sequence of parameters. 你给printf()的模式告诉它应该如何读取参数序列。 You tell printf() to read a %d but gives it a struct test instead of an int . 你告诉printf()读取%d但是给它一个struct test而不是int This messes the whole thing because struct test is dumped in the stack and it takes a lot more space than an int would. 这会使整个事情变得混乱,因为struct test被转储到堆栈中,并且它需要比int更多的空间。

printf() patterns can only support primitives and pointers to null-terminated strings as parameters. printf()模式只能支持原语和指向以null结尾的字符串作为参数的指针。 It doesn't have the ability to print a struct . 它没有打印struct的能力。

printf("t:%d, i:%d, j:%d\n", t, t.i, t.j); 

The first variable on this line, t, is a structure, and you attempted to output it as a digit. 该行的第一个变量t是一个结构,您试图将其作为数字输出。 Since structures have no values of their own, but contain variables instead, referring to this structure t as having some sort of integer value resulted in unexpected results. 由于结构没有自己的值,而是包含变量,因此将此结构称为具有某种整数值会导致意外结果。

When printing the struct, you are actually printing the first 2 ints. 打印结构时,实际上是打印前2个整数。 Then ti is printed as the last int. 然后将ti打印为最后一个int。 then tj is ignored. 那么tj被忽略了。 This happens because your struct consists of 2 int's that are placed in memory in that order. 发生这种情况是因为你的结构由2个int组成,这些int按顺序放在内存中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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