繁体   English   中英

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

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

我有一个如下所示的结构:

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

然后我尝试在主结构中填充结构:

#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;
}

然后,当我查看输出时,我发现第二个 strcpy() 之后的 printf() 不会运行,并且代码会停止:

70468878, 1.0
Before 2nd strcpy.

那么有人可以告诉我我做错了什么吗?

Hashtable_Entry_t* student;
Hashtable_Entry_t* student2;

studentstudent2未初始化的指针。 如果您不初始化它们,那么它们将指向一些随机内存地址。

您可以直接使用Hashtable_Entry_t类型的变量,而不是使用指针。

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

如果你真的想使用指针,那么你可以通过以下方式初始化它们:

#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