C -- 结构体和指针基础题

标签 c struct

所以我现在正在尝试学习 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 做这样的事情(未测试)

int iStringLength = strlen(name);
for (i = 0; i < iStringLength; i++) {
    s->name[i] = name[i];
}

但请确保长度不超过您的数组大小。

这也是错误的

Student* makeAndrew(void) {
   Student s;
   setName(&s, "Andrew");
   setStudentID(&s, 12345678);
   return &s; 
}

因为 s 对象在函数退出时被销毁 - 它在函数范围内是局部的,但您返回一个指向它的指针。因此,如果您尝试使用此指针访问该结构,它将无效,因为该实例不再存在。如果你想这样做,你应该使用 malloc 动态分配它。或者根本不返回指针并使用 @Andrew 的替代选项。

关于C -- 结构体和指针基础题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12338413/

相关文章:

c - 在内核空间将__be32 ip地址转换为char的方法

c - 指向结构的指针

c - 先进先出 (FIFO) 问题

C - 将结构写入文件 (.pcap)

c - 不应该在 API 中使用枚举吗?

无法在 Centos 中的 FT230X 中设置 GPIO 引脚

c - C : is the manual wrong? 中的目录名()

c++ - 带结构的模板

c - ffmpeg/libavfilter 中的字幕

c++ - 给定这两个值的函数会产生第三个值?