设置结构指针的整数会产生分段错误

时间:2019-03-08 04:34:51

标签: c

我正在传递一个指向结构的指针,我想将此结构的成员mn设置为数字33。但是,我遇到了细分问题。发生什么事了?

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

1 个答案:

答案 0 :(得分:2)

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

这是使用堆栈内存的一种方法,您也可以malloc并使用堆内存

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

这些都应该起作用。