그래서 지금 C를 배우려고 노력하고있어, 나는 몇 가지 기본적인 구조체 질문 :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)
s->name = name;
}
/* 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;
}
포인터에 대한 이해를 높이기 위해 코드에 주석을 달았습니다. 나는 그들이 모두 정확 했길 바래.
어쨌든 setName과 setStudentID가 올바르지 않다고 느끼지만 그 이유는 정확히 알 수 없습니다. 누군가 설명 할 수 있습니까? 감사!
편집 : s->name
이후
char temp
int i;
for (i = 0, temp = &name; temp != '\0'; temp++, i++) {
*((s->name) + i) = temp;
strNcpy. 초보자 나쁜 습관을 배우지 마십시오. – nothrow
감사합니다. 그렇다면 어떻게하면 strcpy없이 수동으로 이렇게 할 수 있을까요? for (i = &name; i! = '\ 0'; i ++)? –
'name' 인수의 길이를 확인하십시오 ('strlen'으로 이것을 할 수 있습니다). 그리고 배열에 복사하는 각 인덱스를 반복하십시오. 배열의 길이를 초과하지 않는지 확인하십시오. – mathematician1975