首页 > 解决方案 > 无法在库中定义的结构上存储值

问题描述

主要:

#include stdio.h

#include stdlib.h

#include string.h

#include dictionary.h


int main( int argc, char ** argv ){

  dictionary_t dictionary = NULL;
  dictionary->entries = 1;
  return 0;
}

//在标题中

#ifndef DICTIONARY_H

#define DICTIONARY_H

struct dictionary_s{

  char * name;
  llist_t content;
  int entries;    
};
typedef struct dictionary_s* dictionary_t;

#endif

//它编译但在控制台屏幕中显示分段错误(核心转储)。我已经尝试了几乎所有我能想到的并检查了几个帖子,但我一直无法解决这个问题。

标签: c

解决方案


In main:

#include stdio.h

#include stdlib.h

#include string.h

#include dictionary.h


int main( int argc, char ** argv ){

  //dictionary_t dictionary = NULL;//This was your old line that leads to a null pointer voilation..
  dictionary_t dictionary = (dictionary_t *) malloc(sizeof(dictionary_t));
  if( NULL == dictionary){
    //malloc failed, what do you wanna do now?
    printf("Malloc failed\n");
    //exit(-1);
    while(1){} //just spin forever so you can see the error i suppose?
  }
  dictionary->entries = 1;
  return 0;
}

这是一个 malloc 示例,堆栈示例类似但不同。 https://en.wikibooks.org/wiki/C_Programming/stdlib.h/malloc


推荐阅读