[英]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;
student
和student2
是未初始化的指針。 如果您不初始化它們,那么它們將指向一些隨機內存地址。
您可以直接使用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.