我正在传递指向结构的指针,我想将这个结构的成员m
和n
设置为数字3
和3
。但是,我遇到了分段错误。发生了什么?
#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;
}
这是一种使用堆栈内存的方法,你可以使用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;
}
其中任何一个都应该有用。