简体   繁体   English

结构指针的分段错误

[英]Segmentation fault for structure pointer

I am new in C, and i wrote the following code 我是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;
}

When I am executing it, it is giving me an error: 当我执行它时,它给我一个错误:

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

In gdb:- 在gdb中:

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

What could be the reason??? 可能是什么原因???

Thanks. 谢谢。

You have declared two pointers, but you haven't allocated any memory for them to point to. 您已经声明了两个指针,但是尚未为它们指向分配任何内存。 The pointers are pointing to invalid memory. 指针指向无效的内存。

Try this: 尝试这个:

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

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

You can also declare variables on the stack and assign their addresses to pointers. 您还可以在堆栈上声明变量并将其地址分配给指针。

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

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

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