Objective-C Struct problems -
i have student structure provides following code:
#import <foundation/foundation.h> #import "grades.m" #import <stdio.h> struct student { nsstring *myname; struct grades *mygrades; }; void setname(struct student *s, nsstring *name); void ssetgrades(struct student *s, nsstring *gradelist); void setname(struct student *s, nsstring *name) { s->myname = name; } void ssetgrades(struct student *s, nsstring *gradelist) { printf("\n\nworking\n\n"); setgrades(s->mygrades, gradelist); printf("\n\nworking"); }
i have grades structure provides following:
#import <stdio.h> #import <foundation/foundation.h> #define null null struct grades { double sgrades[100]; int length; }; void setgrades(struct grades *grades, nsstring *gradelist); void setgrade(int spot, double grade, struct grades *grades); void setgrades(struct grades *grades, nsstring *gradelist) { nsstring *a = [gradelist substringtoindex:1]; nsstring *b = [gradelist substringwithrange:nsmakerange(3, 19)]; int ln = [a integervalue]; grades->length = ln; double grade; int x = 1; int prev = 1; int y; int z = 0; for(y=0;y<ln;y++) { while(x < [b length] && [b characteratindex:x] != ' ') { z++; x++; } nsstring *sub = [b substringwithrange:nsmakerange(prev, z)]; grade = [sub doublevalue]; printf("%d %d %d %lf\n", y, prev, z, grade); prev += z+1; x++; z=0; setgrade(y, grade, grades); } } void setgrade(int spot, double grade, struct grades *grades) { grades->sgrades[spot] = grade; }
and finally, have main function following:
#import <foundation/foundation.h> #import "grades.m" #import "student.m" #import <stdio.h> int main (int argc, const char * argv[]) { nsautoreleasepool * pool = [[nsautoreleasepool alloc] init]; struct grades test; setgrades(&test, @"5 - 90 85 95.5 77.5 88"); tostring(&test); printf("\nsum = %lf", getsum(&test)); printf("\nnum grades = %d", getnumgrades(&test)); printf("\nlow grade = %lf", getlowgrade(&test)); printf("\nhigh grade = %lf", gethighgrade(&test)); struct student stu; setname(&stu, @"billy bob"); ssetgrades(&stu, @"5 - 90 85 95.5 77.5 88"); [pool release]; return 0; }
now whenever ssetgrades (&stu, @"5 - 90 85 95.5 77.5 88")
line in main, freezes , says program has stopped working. guesses why , if so, how can fix error?
note: done in notepad++ on windows 7
your primary issue definition of student
structure. change grades
reference isn't pointer:
struct student { nsstring *myname; struct grades mygrades; };
the problem pointer never initialize pointer. removing pointer memory issues causing crash go away.
as result of change, need change few other things. call setgrades
needs pass address of mygrades
:
setgrades(&(s->mygrades), gradelist);
even better replace of struct/function code actual classes.
Comments
Post a Comment