简体   繁体   中英

C code in Dev-Cpp breaks in runtime

I have a C code like below.

#include <stdio.h>
#include <stdlib.h>
struct __student{
    char name[20];
    char surname[20];
    int age;
};

typedef struct __student student;

void getStudent(student* stud)
{
    printf("Name: "); scanf("%s",stud->name);
    printf("Surname: "); scanf("%s",stud->surname);
    printf("Age: "); scanf("%d",stud->age);
}

int main(int argc, char *argv[]) 
{
    student* s = (student*)malloc(sizeof(student));
    getStudent(&s);

    return 0;
}

This code compiles without any error or warning in Dev Cpp 5.10.
But When I try to run this application it breaks after i entered age value.
I don't understand what is the problem?

You're passing a student** (that is a pointer to a pointer) where your function is expecting a student* , also it does give a warning(at least on GCC 4.9.2)

Change your code to

int main(int argc, char *argv[]) 
{
    student* s = malloc(sizeof(student)); //also don't cast the malloc
    getStudent(s);
    free(s); //we don't want memory leaks
    return 0;
}

In addition to passing the correct student as said in the answer above,

printf("Age: "); scanf("%s=d",stud->age);

should be

printf("Age: "); scanf("%d", &stud->age);

As you are typing a number that is being assigned to an int .

I might have misunderstood, but there's no errors in your code. It's OK that your program exits as it reaches return 0; in main right after you enter the age.

Here the function returns right after you enter the age

void getStudent(student* stud)
{
printf("Name: "); scanf("%s",stud->name);
printf("Surname: "); scanf("%s",stud->surname);
printf("Age: "); scanf("%s=d",stud->age);
}

Here you're calling getStudent and then returning 0

student* s = (student*)malloc(sizeof(student));
getStudent(&s); // that's incorrect!!
free(s); //remove this if you're using s after this call

return 0;
}

Oh yes! Didn't get this earlier, I'm sorry! You have to use getStudent(s); instead of getStudent(&s);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM