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

问题描述 投票:0回答:1

我正在传递指向结构的指针,我想将这个结构的成员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
1个回答
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;
}

其中任何一个都应该有用。

© www.soinside.com 2019 - 2024. All rights reserved.