我已经初始化了一个struct" treeFarm"以上并正确初始化了这些功能。这是在"插入"用于将新节点插入二叉搜索树的功能。
struct treeFarm * new = malloc(sizeof(struct treeFarm));
char * typeOfTree = malloc(sizeof(char)*20);
new->type = malloc(sizeof(char)*20);
printf("Please enter the lot number: ");
scanf("%d",&new->lotNum);
printf("Please enter the number of trees: ");
scanf("%d",&new->numTrees);
printf("Please enter the age of the trees: ");
scanf("%d",&new->age);
printf("Please enter the type of trees: ");
scanf("%s", typeOfTree);//seg fault happens here
strcpy(new->type, typeOfTree);
答案 0 :(得分:4)
试试这个
scanf("%19s", typeOfTree);
如果您在'\0'
内阅读超过19个字符加上typeOfTree
,则可以进行段错误,未定义行为可以保证。