所以我现在正在努力学习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;
}
Run Code Online (Sandbox Code Playgroud)
我已经对代码进行了评论,试图巩固我对指针的理解; 我希望他们都准确无误.
所以无论如何,我觉得setName和setStudentID不正确,但我不确定为什么.谁能解释一下?谢谢!
编辑:
char temp
int i;
for (i = 0, temp = &name; temp != '\0'; temp++, i++) {
*((s->name) + i) = temp;
Run Code Online (Sandbox Code Playgroud)
您没有使用此复制全名数组
void setName(Student* s, const char* name) {
s->name = name;
}
Run Code Online (Sandbox Code Playgroud)
试试这个
strcpy(s->name,name);
Run Code Online (Sandbox Code Playgroud)
将此字符串复制到structs数组.你不能简单地将指针参数分配给你当前的数组变量.您需要将指向的每个字符复制到name数组的元素中s->name.这strcpy将是做什么 - 它将元素从源复制到目标,直到它找到终止空字符.
编辑:或者您可以strncpy按照评论中的建议使用.检查这个问题及其答案,看看为什么有些人认为这是个好主意为什么要使用strncpy而不是strcpy?