首页 > 解决方案 > 设置结构指针的整数会导致分段错误

问题描述

我正在传递一个指向结构的指针,我想设置这个结构的成员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;
}

标签: c

解决方案


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

其中任何一个都应该工作。


推荐阅读