Search code examples
cdata-structuresstructure

Unable to assign value in variable of Structure in C using Pointer


My Code:-

#include<stdio.h>
struct Demo{
    int value;
};
int main(){
    struct Demo *l;
    l->value=4;
}

Getting Segmentation fault (core dumped)


Solution

  • because L object doesn't point something. use this :

    #include <iostream>
    using namespace std;
    struct Demo
    {
        int val;    
    };
    int main()
    {
        Demo* a = new Demo();
        a->val = 10;
        cout<<a->val;
    }
    

    enter image description here