C Pointer for Struct - Segmentation fault

2020-07-14 12:25发布

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

3条回答
成全新的幸福
2楼-- · 2020-07-14 12:55

Your problem is that you write at random memory locations since you do not initialize your pointers nor allocate memory.

You could do the following:

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

Obviously you need to free them when you are done using them:

free(p);
free(q);
free(r);
查看更多
该账号已被封号
3楼-- · 2020-07-14 12:56

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

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
查看更多
劫难
4楼-- · 2020-07-14 13:12

You're not allocating memory to the pointer. Therefore when you're doing *p and *q and *r you're dereferencing a null pointer (or a random pointer). This leads to a segmentation fault. Use p = malloc(sizeof(int)); when you declare the variables.

查看更多
登录 后发表回答