Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 结构指针的分段错误_C_Segmentation Fault - Fatal编程技术网

C 结构指针的分段错误

C 结构指针的分段错误,c,segmentation-fault,C,Segmentation Fault,我是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;

我是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;
}
在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

您已经声明了两个指针,但尚未为它们分配任何内存。指针指向无效内存

试试这个:

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

您还可以在堆栈上声明变量,并将其地址分配给指针

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