-1

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?

J.Fasterling
  • 31
  • 1
  • 7

1 Answers1

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

Aamir
  • 1,974
  • 1
  • 14
  • 18
  • `#include ` is surely wrong. Aside: [do not cast the return of `malloc`](https://stackoverflow.com/a/605858/2505965) in C. – Oka Jun 27 '22 at 18:37
  • Thanks for the input. I updated my answer but for malloc I did cross verify [here](https://en.cppreference.com/w/c/memory/malloc), it did come from `stdlib.c`. – Aamir Jun 27 '22 at 18:42
  • @Aamir Read it again, *Defined in header ``* is emblazoned immediately above the prototype. There is no `stdlib.c` formally defined in the standard library, nor does it appear anywhere on that page. It is called `stdlib.h` , a *header* file that declares a multitude of things, `malloc` being one of them. – WhozCraig Jun 27 '22 at 20:57
  • Ohh… for some strange reasons, my eyes refuse to recognize the typo error. I intended to mention `.h` not `.c`. Thanks for bringing it into attention. Corrected the typo. – Aamir Jun 28 '22 at 00:53