user125621
user125621

Reputation: 23

Creating and printing pointer based structures in C

I am just learning about structures and I have been able to get them to work just fine when using regular variables. However when I try to do it with a pointer my program will run but it crashes. I am sure I've just got something small wrong...

struct Student{
char firstName[30];
char lastName[30];
float gpa;
int id;
};


int main()
{
struct Student *student;
student = (struct Student*)sizeof(struct Student);
strcpy(student->firstName,"Marlop");
strcpy(student->lastName,"smiitlh");
student->gpa = 4.54;
student->id = 45893;

printf("%s",student->firstName);

return 0;
}

Upvotes: 0

Views: 30

Answers (1)

MikeCAT
MikeCAT

Reputation: 75062

This code

student = (struct Student*)sizeof(struct Student );

makes no sense. This is assigning some (invalid for large chance) meanungless address to student.

You should use malloc() to allocate some memory. Try this:

#include <stdio.h>
#include <stdlib.h>

struct Student{
    char firstName[30];
    char lastName[30];
    float gpa;
    int id;
};


int main(void)
{
    struct Student *student;
    student = malloc(sizeof(struct Student));
    strcpy(student->firstName,"Marlop");
    strcpy(student->lastName,"smiitlh");
    student->gpa = 4.54;
    student->id = 45893;

    printf("%s",student->firstName);

    free(student);
    return 0;
}

Upvotes: 3

Related Questions