簡體   English   中英

結構指針的分段錯誤

[英]Segmentation fault for structure pointer

我是C語言的新手,我寫了以下代碼

#include <stdlib.h>
#include<stdio.h>

typedef struct
{
    int name1;
}check1;
typedef struct
{
    int name2;
}check2;

int main()
{
    check1 *test1;
    check2 *test2;
    test1->name1=1;
    test2->name2=2;
    return 0;
}

當我執行它時,它給我一個錯誤:

$ gcc test1.c
$ ./a.out
Memory fault

在gdb中:

Program received signal SIGSEGV, Segmentation fault.
0x000000000040045e in main ()

可能是什么原因???

謝謝。

您已經聲明了兩個指針,但是尚未為它們指向分配任何內存。 指針指向無效的內存。

嘗試這個:

check1 *test1 = malloc(sizeof(*test1));
if (test1 == NULL)
    // report failure

check2 *test2 = malloc(sizeof(*test2));
if (test2 == NULL)
    // report failure

您還可以在堆棧上聲明變量並將其地址分配給指針。

check checka;
check* pcheck = &checka;
printf("%i",pcheck->name1);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM