[英]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
. 我正在传递一个指向结构的指针,并且我想将此结构的成员m
和n
设置为数字3
和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 这是使用堆栈内存的一种方法,您也可以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;
}
Either of those should work. 这些都应该起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.