我有一个学生结构,提供以下代码:
#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");
}
我有一个成绩结构,提供以下内容:
#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;
}
最后,我有一个主要功能如下:
#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;
}
现在每当我到达主要的ssetGrades (&stu, @"5 - 90 85 95.5 77.5 88")
行时,它就冻结并说该程序已停止工作。任何猜测为什么以及如果是,我该如何解决这个错误?
注意:这一切都在Windows 7上的Notepad ++中完成
答案 0 :(得分:0)
您的主要问题是您对Student
结构的定义。更改Grades
引用,使其不是指针:
struct Student
{
NSString *myName;
struct Grades myGrades;
};
指针的问题是你永远不会初始化指针。通过移除指针,导致崩溃的内存问题将消失。
由于此更改,您需要更改其他一些内容。对setGrades
的调用需要传递myGrades
的地址:
setGrades(&(s->myGrades), gradeList);
更好的方法是用实际的类替换所有这些结构/函数代码。