【发布时间】:2019-12-17 19:11:44
【问题描述】:
在我老师提供给我们的教科书中,有这个 C 代码的示例,当我尝试运行时会出现 Segmentation Fault 错误:
const celula *nulo = NULL;
typedef char informacao;
typedef celula *noh;
typedef celula *arvore;
struct celula {informacao info; noh pai; noh fesq; noh idir;};
...
typedef struct celfloresta celfloresta;
typedef struct celfloresta *floresta;
typedef struct celfloresta *posicfloresta;
struct celfloresta {arvore elem; celfloresta *prox;};
...
void FormarListaNohs(){
floresta p = (floresta)malloc(sizeof(celfloresta));
p->elem->info = '3';
}
...
为什么行
p->elem->info = '3';
这里给出分段错误?
【问题讨论】:
-
malloc也需要内存供elem使用。 -
关于:
const celula *nulo = NULL;这是在定义之前使用celula。建议将该语句移到结构定义之后 -
OT:关于:
floresta p = (floresta)malloc(sizeof(celfloresta));1) 在 C 中,返回的类型是void*,可以分配给任何指针。强制转换只会使代码混乱。建议去掉演员表。 2) 始终检查 (!=NULL) 返回值以确保操作成功。 -
OT: about:
typedef struct celfloresta *floresta;andtypedef struct celfloresta *posicfloresta;and typedef celula *noh;` andtypedef celula *arvore;隐藏typedef中的指针。
标签: c pointers struct segmentation-fault malloc