简体   繁体   中英

Setting integer of a struct pointer gives segmentation fault

I'm passing a pointer to a struct, and I want to set this struct's members m and n to the numbers 3 and 3 . However, I'm getting segmenation fault. What's happening?

#include <stdio.h>

typedef struct Matrix {
    int m; //number of lines
    int n; //number of columns
    float* numbers; //elements of our matrix
} Matrix;

void matrix_create(Matrix* a, const float *array, int lines, int columns)
{   
    a->m = lines;
    a->n = columns;
}


int main()
{
    Matrix* a;
    float b[3][3] = {{1,2,3},{4,5,6},{7,8,9}};
    matrix_create(a, b, 3, 3);
    return 0;
}
#include <stdio.h>

typedef struct Matrix {
    int m; //number of lines
    int n; //number of columns
    float* numbers; //elements of our matrix
} Matrix;

void matrix_create(Matrix* a, const float *array, int lines, int columns)
{   
    a->m = lines;
    a->n = columns;
}


int main()
{
    Matrix* a;
    Matrix temp;//Stack Matrix
    float b[3][3] = {{1,2,3},{4,5,6},{7,8,9}};
    a = &temp; //Stack memory
    matrix_create(a, b, 3, 3);
    return 0;
}

Here is a way to do it with stack memory, you can malloc and use heap memory too

#include <stdio.h>

typedef struct Matrix {
    int m; //number of lines
    int n; //number of columns
    float* numbers; //elements of our matrix
} Matrix;

void matrix_create(Matrix* a, const float *array, int lines, int columns)
{   
    a->m = lines;
    a->n = columns;
}


int main()
{
    Matrix* a = malloc(sizeof(Matrix));
    float b[3][3] = {{1,2,3},{4,5,6},{7,8,9}};
    matrix_create(a, b, 3, 3);
    return 0;
}

Either of those should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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