c++visual-studio-codescopeg++global-namespace

Showing Garbage values in Structures in c++


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


Solution

  • 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};