2

I have a problem with strcpy in C. My Code:

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;
}

and my main 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;
}

The Problem is the printf statement returns TestABC instead of just Test. I just dont get it why. I just want the name not the name and the grades togehter in my printf statement. Can anyone help?

1
  • Look at your Student struct and ask yourself where you're storing those strings. I don't see any arrays, do you? Commented May 7, 2016 at 20:23

1 Answer 1

2

You've got several problems here.

First, change your struct declaration to allocate space for your character strings. I randomly picked 100 for array sizes; change that to whatever size makes sense.

typedef struct {
    char name[100];  /**< name of Student */
    char grades[100];/**< grades of labs */
    float mark;      /**< float as mark of labs */
} Student;

Next, change your new_student function as follows:

Student *test;
test = malloc(sizeof(Student));

strcpy(test->name, name);
strcpy(test->grades, noten);

Finally, fix your printf statement in main to look like this:

printf("%s", s->name);
Sign up to request clarification or add additional context in comments.

2 Comments

ty that helped me to fix the problem. I just started to learn C, so im very thankful for any advice :).
@member2 You're welcome, but the usual way to express appreciation is to upvote and accept the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.