Showing Garbage values in Structures in c++

450 Views Asked by At
#include<iostream>
using namespace std;
struct student
{
  char name [50];
  int roll;
  float marks;
}s = {"Karthik",1,95.3};
int main()
{
  struct student s;
  cout<<"\nDisplaying Information : "<<endl;
  cout<<"Name  : "<<s.name<<endl;
  cout<<"Roll  : "<<s.roll<<endl;
  cout<<"Marks : "<<s.marks<<endl;
   return 0;
} 

OutPut :

Displaying Information : 
Name  : 
Roll  : 21939
Marks : 2.39768e-36

Compiled on Visual-Studio-Code(on linux os) what should i do to get correct output.

2

There are 2 best solutions below

0
Paul Evans On BEST ANSWER

Because you're using this uninitialized struct:

struct student s; 

which hides the global s.

Instead, initialize it in main:

student s = {"Karthik",1,95.3};
0
Vlad from Moscow On

Your declared two objects of the type student.

The first one is declared in the global namespace

struct student
{
  char name [50];
  int roll;
  float marks;
}s = {"Karthik",1,95.3};

and is initialized and the second one in the block scope of the function main

struct student s;

that is moreover not initialized.

The object declared in the block scope hides the object with the same name declared in the global namespace.

Either remove the local declaration or use a qualified name to specify the object declared in the global namespace as for example

  cout<<"\nDisplaying Information : "<<endl;
  cout<<"Name  : "<< ::s.name<<endl;
  cout<<"Roll  : "<< ::s.roll<<endl;
  cout<<"Marks : "<< ::s.marks<<endl;