Cyber Security
Cyber Security

Reputation: 13

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)

Upvotes: 0

Views: 293

Answers (2)

Badhan Sen
Badhan Sen

Reputation: 737

You have to allocate memory to l Demo object. In C you have to allocate memory using malloc. See the code for a better understanding.

#include<stdio.h>
#include<malloc.h>

struct Demo{
    int value;
};

int main(){
    struct Demo *l = (struct Demo*)malloc(sizeof (struct Demo));
    l->value = 4;
    printf("%d\n", l->value);
    return 0;
}

Output

4

Upvotes: 1

Salar Ashgi
Salar Ashgi

Reputation: 126

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

Upvotes: 1

Related Questions