2013-02-15 61 views
0

我应该填写的代码很容易。代码中的逻辑错误

#define MAX_NAME_LEN 128 
typedef struct { 
char name[MAX_NAME_LEN]; 
unsigned long sid; 
} Student; 
/* return the name of student s */ 
const char* getName(const Student* s) { 
return s->name; 
} 
/* set the name of student s */ 
void setName(Student* s, const char* name) { 
/* fill me in */ 
}/* return the SID of student s */ 
unsigned long getStudentID(const Student* s) { 
/* fill me in */ 
} 
/* set the SID of student s */ 
void setStudentID(Student* s, unsigned long sid) { 
/* fill me in */ 
} 

但是它说什么是以下函数中的逻辑错误?

Student* makeDefault(void) { 
Student s; 
setName(&s, "John"); 
setStudentID(&s, 12345678); 
return &s; 
} 

我没有看到任何问题。我测试了它。它工作正常。

是因为这应该是一个无效函数,不需要返回任何东西?

+0

谁这么说?... – 2013-02-15 08:27:55

回答

0

你不能返回一个指向本地声明变量(Student's)的指针。变量“s”将在返回后消失(变成垃圾)。

相反,您需要先分配一个学生。

你或许应该这样做:

void makeDefault(Student* pS) { 
setName(pS, "John"); 
setStudentID(pS, 12345678); 
} 

然后让调用应用程序分配的学生。

+0

谢谢,如果我不是1级,我肯定会赞扬这一点。 – user2054534 2013-02-15 08:30:25