结构指针错误

Tha*_*raj 1 c struct pointers

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; }
Run Code Online (Sandbox Code Playgroud)

我尝试运行此程序时出现分段错误.任何人都可以证明这个理由吗?

我也尝试过

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; }
Run Code Online (Sandbox Code Playgroud)

现在我收到的错误就像

funptrinstrct.c: In function `main': funptrinstrct.c:17: error: conversion to non-scalar type requested
Run Code Online (Sandbox Code Playgroud)

对此的回答也是可以理解的.

pax*_*blo 5

对于第一个问题,您创建一个指针h而不初始化它,然后您立即尝试取消引用它h->f.b.

对于第二个,你应该投射g*,而不是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());
}
Run Code Online (Sandbox Code Playgroud)

那是因为它g是一个结构,而不是指向结构的指针.上面的代码7按预期输出.