【问题标题】:strcpy issue with char pointer in cc中的char指针的strcpy问题
【发布时间】: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 结构并问自己将这些字符串存储在哪里。我没有看到任何数组,是吗?

标签: pointers struct malloc


【解决方案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);

最后,将main 中的printf 语句修改为如下所示:

printf("%s", s->name);

【讨论】:

  • 帮助我解决问题的方法。我刚开始学习 C,所以我非常感谢任何建议:)。
  • @member2 不客气,但表达感谢的通常方式是点赞并接受答案。
猜你喜欢
  • 2017-03-30
  • 2021-08-11
  • 2011-12-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多