问题描述:

I need to pass pointer to function but it doesn't work output is empty.

i study this pointer 1 week ago at my university but it's very confused.

thank you for your advance.

code below and 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 this Course is = ");

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 is output

网友答案:

Firstly, this question looks fairly ridiculous, especially with a struct name of "Nooooooooooooooooooooooo", it's probably a waste of people's time trying to answer.

Secondly, your terminology is way off. Passing a pointer to a structure is very different from a pointer to a function!

However in your code, the main issue is with this line:

void GetData(course *newnode,course *root,course *last)

Do you actually know what you have here? Well, you have 3 local pointers which when your program starts are all null or uninitialised. Then in your function, you malloc() some ram and use these local pointers to store the address of this allocated block of memory. However, you don't seem to understand that these are local copies of the pointers that you've passed in, so when your function ends, they're going to disappear when the stack unwinds.

If you're going to want to return the address of the memory you allocate to the calling function, you're going to need to pass the address of the pointer and then make your function take a double dereference.

Something like this...

course *c;

GetData(&c);

void GetData(course **c)
{
    *c = (course*)malloc(sizeof(course));
    ...
    ...
}
相关阅读:
Top