在C

2016-05-07 39 views
1

字符指針strcpy的問題,我有一個問題,在strcpy的C.我的代碼:在C

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語句中使用名稱而不是名稱和成績。誰能幫忙?

+0

看看你'Student'結構和問問你自己在哪裏存儲這些字符串。我沒有看到任何陣列,是嗎? –

回答

0

這裏有幾個問題。

首先,更改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); 
+0

ty幫助我解決了這個問題。我剛開始學習C,所以我非常感謝任何建議:)。 – member2

+0

@ member2不用客氣,但通常表達讚賞的方式是贊成並接受答案。 –