我在C中的strcpy有问题。我的代码:
student.h
#include <stdlib.h>
#include <string.h>
typedef struct {
char *name; /**< char pointer to name of Student */
char *grades; /**< char pointer to grades of labs */
float mark; /**< float as mark of labs */
} Student;
Student *new_student(char *, char *);
student.c
include "student.h"
Student *new_student(char *name, char *grades) {
if (name == NULL || strlen(name) == 0) return NULL;
char *marks = "";
//if (grades == NULL) grades = "";
if(grades == NULL){
marks= "";
}
else{
marks= grades;
}
Student *test;
test = (Student*) malloc(sizeof(Student));
(void)strcpy(&test->name, name);
(void)strcpy(&test->grades, noten);
return test;
}
和我的主要check.c
#include <stdlib.h>
#include "student.h"
int main() {
Student *s;
s = new_student("Test", "ABC");
printf("%s",&s->name);
/*(void)test_student(0, NULL);*/
return EXIT_SUCCESS;
}
问题是printf语句返回TestABC而不仅仅是Test。我只是不明白为什么。我只想在我的printf声明中使用名称而不是名称和等级。有人可以帮忙吗?
答案 0 :(得分:1)
你在这里遇到了几个问题。
首先,更改struct
声明以为字符串分配空间。我随机挑选100个数组大小;把它改成任何有意义的大小。
typedef struct {
char name[100]; /**< name of Student */
char grades[100];/**< grades of labs */
float mark; /**< float as mark of labs */
} Student;
接下来,按如下方式更改new_student
功能:
Student *test;
test = malloc(sizeof(Student));
strcpy(test->name, name);
strcpy(test->grades, noten);
最后,修复printf
中的main
语句,如下所示:
printf("%s", s->name);