C结构指针 - 分段故障

时间:2010-11-14 22:44:41

标签: c pointers struct

我遇到了这个程序的问题。这非常简单。我需要从我创建的指针中为我的结构赋值,但是我一直遇到分段错误。任何想法我做错了什么:

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

struct problem37
{
    int a;
    int b;
    int c;
};

int main()
{
    printf("Problem 37\n");

    //create struct
    struct problem37 myStruct;

    //create the pointer
    int* p;
    int* q;
    int* r;

    *p = 1;
    *q = 5;
    *r = 8;

    //read the data into the struct using the pointers
    myStruct.a = *p;
    myStruct.b = *q;
    myStruct.c = *r;

    printf("%d\n", myStruct.a);
    printf("%d\n", myStruct.b);
    printf("%d\n", myStruct.c);

    return 0;
}

3 个答案:

答案 0 :(得分:7)

您正在为*p*q*r分配一个值,但它们未初始化:它们是指向随机内存的指针。

您需要初始化它们,或者为它们分配在堆中分配的新值(使用malloc):

int *p = (int*) malloc( sizeof(int) );
*p = 1;

或使它们指向已存在的值:

int x;
int *p = &x;
*p = 1; // it's like doing x=1

答案 1 :(得分:6)

您的问题是您在随机内存位置写入,因为您没有初始化指针也没有分配内存。

您可以执行以下操作:

int* p = malloc(sizeof(int));
int* q = malloc(sizeof(int));
int* r = malloc(sizeof(int));

显然你需要在使用它们时释放它们:

free(p);
free(q);
free(r);

答案 2 :(得分:2)

您没有为指针分配内存。因此,当您执行* p和* q和* r时,您将取消引用空指针(或随机指针)。这导致分段错误。使用p = malloc(sizeof(int));当你声明变量时。

相关问题