结构的C指针-分段错误 [英] C Pointer for Struct - Segmentation fault

查看:82
本文介绍了结构的C指针-分段错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am having problems with this program. It's very simply. I need to assign values to my struct from the pointers I created, but I keep getting a segmentation fault. Any ideas what I'm doing wrong:

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

推荐答案

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

Your are assigning a value to *p, *q and *r, but they are not initialized: they're pointers pointing to random memory.

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

You need to initialize them, either assigning them a new value allocated in the heap (with malloc):

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

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

or making them point to an already existent value:

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

这篇关于结构的C指针-分段错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆