【发布时间】:2016-05-07 12:24:46
【问题描述】:
我在 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;
}
和我的主要检查.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 语句中的名称而不是名称和等级。有人可以帮忙吗?
【问题讨论】:
-
查看您的
Student结构并问自己将这些字符串存储在哪里。我没有看到任何数组,是吗?