user2975112
user2975112

Reputation: 13

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("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. Thanks.

Upvotes: 1

Views: 64

Answers (3)

Havenard
Havenard

Reputation: 27854

The pattern you give printf() tells it how it should read the sequence of parameters. You tell printf() to read a %d but gives it a struct test instead of an 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.

printf() patterns can only support primitives and pointers to null-terminated strings as parameters. It doesn't have the ability to print a struct.

Upvotes: 2

River
River

Reputation: 63

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. 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.

Upvotes: 1

Arjen
Arjen

Reputation: 646

When printing the struct, you are actually printing the first 2 ints. Then t.i is printed as the last int. then t.j is ignored. This happens because your struct consists of 2 int's that are placed in memory in that order.

Upvotes: 0

Related Questions