Search code examples
cpointersstructprintfstrcpy

C code crashes when running strcpy() for the second time


I have a struct that looks like the following:

typedef struct
{
    char matrikelnr[10];
    double note;
} Hashtable_Entry_t;

And then I try to fill the struct in the main:

#include <stdio.h>
#include <string.h>


int main(int argc, char const *argv[])
{
    Hashtable_Entry_t* student;
    strcpy(student->matrikelnr, "70468878");
    student->note = 1.0;
    printf("%s, %.1f \n", student->matrikelnr, student->note);

    Hashtable_Entry_t* student2;
    printf("Before 2nd strcpy.\n");
    strcpy(student2->matrikelnr, "70468878");
    printf("Before 2nd strcpy.\n");
    student2->note = 1.0;
    printf("%s, %.f", student2->matrikelnr, student2->note);
    
    return 0;
}

And when I then take a look at the output I see that the printf() after the second strcpy() wont run and the code just stops:

70468878, 1.0
Before 2nd strcpy.

So can someone tell me what is it that I'm doing wrong?


Solution

  • Hashtable_Entry_t* student;
    Hashtable_Entry_t* student2;
    

    student and student2 are uninitalised pointer. If you not initialize them then they will point to some random memory address.

    Instead of using pointer you can directly use the variable of Hashtable_Entry_t type.

    Hashtable_Entry_t student;
    strcpy(student.matrikelnr, "70468878");
    student.note = 1.0;
    printf("%s, %.1f \n", student.matrikelnr, student.note);
    

    If you really wants to use pointer, then you can initialize them in the following ways:

    #include <stdlib.h>  // for malloc
    
    Hashtable_Entry_t* student = malloc(sizeof(Hashtable_Entry_t));
    strcpy(student->matrikelnr, "70468878");
    student->note = 1.0;
    printf("%s, %.1f \n", student->matrikelnr, student->note);
    
    // Assign address of Hashtable_Entry_t variable
    Hashtable_Entry_t student;
    Hashtable_Entry_t* student_ptr = &student;
    strcpy(student_ptr->matrikelnr, "70468878");
    student_ptr->note = 1.0;