[英]function does not return root node
我想我的 function 返回我的链表的根节点。 Function 在操作中确实工作得非常清楚。 但不会将根节点返回到主 function。 我想让根节点在 main 之后使用它。 谢谢。
struct input* parse_the_input(char str[250]) {
int spacecount=0;
int minispacecount;
int i,j;
struct input* root;
struct input* realroot=(struct input*)malloc(sizeof(struct input));
realroot=root;
char var[10];
for(i=0;i<strlen(str);i++) {/*space number in the input string is equal to input number in the string. */
if(str[i]==' ')
spacecount++;
}
/*deleting "INPUT" part of string in order to read names of inputs as string */
for(i=0;i<5;i++)
str[i]=' ';
j=6;
for(i=0;i<spacecount;i++) {
root=(struct input*)malloc(sizeof(struct input));
sscanf(str,"%s",var);
strcpy(root->name,var);
root->Gate=(struct gate*)malloc(sizeof(struct gate));
root->Gate->type=0;
strcpy(root->Gate->name,var);
if(i==spacecount-1) /*if loop does not break there, program reads rest of string which is full of '\0's. It may cause segmentation fault */
break;
minispacecount=0;
while(minispacecount!=1) { /*filling readed strings with whitespace characters in order to read other string */
if(str[j]==' ')
minispacecount++;
else
str[j]=' ';
j++;
}
root=root->next;
}
return realroot;
}
int main() {
FILE *fcircuitp=fopen("circuit.txt","r");
char str[250];
struct input* root=(struct input*)malloc(sizeof(struct input));
/* reading circuit file with fgets */
while( fgets (str, 250, fcircuitp)!=NULL ) {
if(str[0]=='I') {/* if it is input, then parse the input. */
root=parse_the_input(str);
printf("%s",root->name);
}
}
}
首先,这三行没有意义:
struct input* root;
struct input* realroot=(struct input*)malloc(sizeof(struct input));
realroot=root;
第一个定义root
但不初始化它。 这意味着它将具有不确定的价值。 取消引用此指针将导致未定义的行为。
第二行定义realroot
并将其初始化为指向您分配的一些 memory。
当您将root
的不确定值分配给 realroot 时,第三行丢弃了最近分配的realroot
。 这将导致memory 泄漏,并且您从 function 返回无效指针。
您似乎误解了指针和动态分配的工作原理。 请花点时间多学习你的课本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.