gpt4 book ai didi

c - 设置结构指针的整数会导致段错误

转载 作者:太空宇宙 更新时间:2023-11-04 07:48:59 25 4
gpt4 key购买 nike

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

这些都应该有效。

关于c - 设置结构指针的整数会导致段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55056787/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com