简体   繁体   English

第二次运行 strcpy() 时 C 代码崩溃

[英]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:然后,当我查看输出时,我发现第二个 strcpy() 之后的 printf() 不会运行,并且代码会停止:

70468878, 1.0
Before 2nd strcpy.

So can someone tell me what is it that I'm doing wrong?那么有人可以告诉我我做错了什么吗?

Hashtable_Entry_t* student;
Hashtable_Entry_t* student2;

student and student2 are uninitalised pointer. studentstudent2未初始化的指针。 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类型的变量,而不是使用指针。

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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