Thangaraj
Thangaraj

Reputation: 3184

Struct pointer errors

int d() {return 0;} int i() {return 7;}

struct a { int(*b)(); }c={d};

typedef struct e{ struct a f; }g;

main() { struct e *h; h->f.b = i; }

I am getting segmentation fault when I try to run this program. Can anyone justify the reason?

And I also tried like

int d() {return 0;} int i() {return 7;}

struct a { int(*b)(); }c={d};

typedef struct e{ struct a f; }g;

main() { struct e *h; h = (g)malloc(sizeof(g)); h->f.b = i; }

Now I am getting errors like

funptrinstrct.c: In function `main': funptrinstrct.c:17: error: conversion to non-scalar type requested

Answer for this also would be appreciable.

Upvotes: 1

Views: 559

Answers (4)

paxdiablo
paxdiablo

Reputation: 881463

For the first question, you create a pointer h without initialising it, then you immediately try to dereference it with h->f.b.

For the second one, you should be casting to g*, not g:

#include <stdio.h>

int d (void) { return 0; }
int i (void) { return 7; }

struct a { int(*b)(void); } c = {d};
typedef struct e { struct a f; } g;

int main (void) {
    struct e *h = (g*)malloc (sizeof (g));
    h->f.b = i;
    printf ("%d\n", h->f.b());
}

That's because g is a structure, not a pointer to a structure. The code above outputs 7 as expected.

Upvotes: 5

Alam
Alam

Reputation: 1596

change your main body to

struct e *h = (struct e *)malloc(sizeof(struct e)); 
h->f.b = i;

It will work. moral:

Never ignore warnings

.

Upvotes: 0

Mattias Holm
Mattias Holm

Reputation:

struct e *h is an undefined pointer, either declare it on the stack by dropping the '*' or allocate it with malloc.

Upvotes: 0

Bwmat
Bwmat

Reputation: 4578

h is an uninitialized pointer.

Trying to dereference it is a big no-no

Upvotes: 0

Related Questions