pass pointer of struct in c programming -
i need pass pointer function doesn't work output empty.
i study pointer 1 week ago @ university it's confused.
thank advance.
code below , output :
#include<stdio.h> #include<string.h> #include<stdlib.h> typedef struct nooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo{ char courseid[10]; char coursename[50]; float score; struct nooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo *next; }course; void getdata(course *newnode,course *root,course *last) { char courseid[10],coursename[50]; float score; file *input; input = fopen("course.txt","r"); fscanf(input,"%s %s %f",&courseid,&coursename,&score); while(!feof(input)) { newnode = (course*)malloc(sizeof(course)); strcpy(newnode->courseid,courseid); strcpy(newnode->coursename,coursename); newnode->score = score; newnode->next = null; if(root == null) { root = newnode; last = newnode; } else { last->next = newnode; last = newnode; } fscanf(input,"%s %s %f",&courseid,&coursename,&score); } } void checkscore(course *run,course *root) { run = root; while(run != null) { if(run->score >= 80) { printf("course id = %s\n",run->courseid); printf("course name = %s\n",run->coursename); printf("your grade of course = "); if(run->score < 50) { printf("d"); } else if(run->score < 60) { printf("c"); } else if(run->score < 70) { printf("b"); } else { printf("a"); } } run = run->next; } } int main() { course *root = null,*last,*newnode,*run; int i,cnt; getdata(newnode,root,last); checkscore(run,root); return 0; }
this output
firstly, question looks ridiculous, struct name of "nooooooooooooooooooooooo", it's waste of people's time trying answer.
secondly, terminology way off. passing pointer structure different pointer function!
however in code, main issue line:
void getdata(course *newnode,course *root,course *last)
do know have here? well, have 3 local pointers when program starts null or uninitialised. in function, malloc() ram , use these local pointers store address of allocated block of memory. however, don't seem understand these local copies of pointers you've passed in, when function ends, they're going disappear when stack unwinds.
if you're going want return address of memory allocate calling function, you're going need pass address of pointer , make function take double dereference.
something this...
course *c; getdata(&c); void getdata(course **c) { *c = (course*)malloc(sizeof(course)); ... ... }
Comments
Post a Comment