所以我想学C,现在,我有一些基本的结构问题,我想搞清楚:Ç - 结构体和指针基本问题
基本上围绕这个代码片段一切中心:
#include <stdio.h>
#include <stdlib.h>
#define MAX_NAME_LEN 127
typedef struct {
char name[MAX_NAME_LEN + 1];
unsigned long sid;
} Student;
/* return the name of student s */
const char* getName (const Student* s) { // the parameter 's' is a pointer to a Student struct
return s->name; // returns the 'name' member of a Student struct
}
/* set the name of student s
If name is too long, cut off characters after the maximum number of characters allowed.
*/
void setName(Student* s, const char* name) { // 's' is a pointer to a Student struct | 'name' is a pointer to the first element of a char array (repres. a string)
char temp;
int i;
for (i = 0, temp = &name; temp != '\0'; temp++, i++) {
*((s->name) + i) = temp;
}
/* return the SID of student s */
unsigned long getStudentID(const Student* s) { // 's' is a pointer to a Student struct
return s->sid;
}
/* set the SID of student s */
void setStudentID(Student* s, unsigned long sid) { // 's' is a pointer to a Student struct | 'sid' is a 'long' representing the desired SID
s->sid = sid;
}
我已经评论了代码,以巩固我对指针的理解;我希望他们都准确。
另外,我有另一种方法,
Student* makeAndrew(void) {
Student s;
setName(&s, "Andrew");
setStudentID(&s, 12345678);
return &s;
}
,我敢肯定是错误的以某种方式......我也觉得我的setName被错误地执行。
任何指针? (无双关语)
不用手动复制,使用例如'strcpy'。 –
'setName'不检查输入字符串长度,所以它可能会崩溃为足够长的输入字符串。你需要'temp'='\ 0'&&我
Vlad