【问题标题】:C Pointer for Struct - Segmentation fault结构的 C 指针 - 分段错误
【发布时间】:2010-11-14 22:44:40
【问题描述】:

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

#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;
}

【问题讨论】:

  • 你认为你的指针指向哪里?

标签: c pointers struct


【解决方案1】:

您正在为*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

【讨论】:

    【解决方案2】:

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

    您可以执行以下操作:

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

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

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

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-07-12
        • 1970-01-01
        • 2012-11-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多