2012-09-09 2 views
0

그래서 지금 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; 

답변

5

당신은 당신의 구조체 배열에이 문자열을 복사하려면이

strcpy(s->name,name); 

시도이

void setName(Student* s, const char* name) { 
    s->name = name; 
} 

와 전체 이름 배열을 복사하지 않습니다. 현재 가지고있는 배열 변수에 포인터 인수를 할당하기 만하면됩니다. name이 가리키는 각 문자를 배열 s->name의 요소에 복사해야합니다. 이것은 strcpy이 수행하는 것입니다. 종료 문자를 찾을 때까지 소스에서 대상으로 요소를 복사합니다.

편집 : 또는 strncpy을 주석에 제안 된대로 사용할 수 있습니다. 이 질문과 그 대답을 확인하여 어떤 사람들이 이것이 좋은 생각이라고 생각하는 이유를 확인하십시오. Why should you use strncpy instead of strcpy?

+0

strNcpy. 초보자 나쁜 습관을 배우지 마십시오. – nothrow

+0

감사합니다. 그렇다면 어떻게하면 strcpy없이 수동으로 이렇게 할 수 있을까요? for (i = &name; i! = '\ 0'; i ++)? –

+0

'name' 인수의 길이를 확인하십시오 ('strlen'으로 이것을 할 수 있습니다). 그리고 배열에 복사하는 각 인덱스를 반복하십시오. 배열의 길이를 초과하지 않는지 확인하십시오. – mathematician1975

3
s->name = name; 

배열입니다 당신은 (그것이 수정 좌변이 아니다)이에 할당 할 수 없습니다 - 그것은 컴파일러 오류가 있어야한다. strcpy 또는 memcpy을 입력해야하지만 name이 너무 커서는 안됩니다.

1

setStudentID는 완벽하게 훌륭하지만 setStudentName은 아닙니다. 배열에 char *를 할당하려고하는데 작동하지 않습니다. strcpy과 같이 요소 단위로 복사하는 함수를 사용해야합니다.