c - 设置结构指针的整数会导致分段错误
问题描述
我正在传递一个指向结构的指针,我想设置这个结构的成员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;
}
其中任何一个都应该工作。
推荐阅读
- javascript - 使用反应钩子切换对象内部的状态
- django - 列出模型字段Django?
- javascript - 相机动画旋转问题
- javascript - 如何让我的状态在 API 数据触发之前等待它?
- python - 使用 HMM 模型重建信号
- javascript - 如何定义事件处理函数来组合事件监听器
- python - 使用 Python Qt5 的可变引用
- webpack - scss 不适用于 vue3 应用程序(TypeError: this.getOptions is not a function)
- custom-post-type - 如何使用 walker-nav 和 elementor 内容生成器创建大型菜单
- javascript - 如何记录所有事件(使用操作)具有事件侦听器的 DOM 元素?