所以我想學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