本文介绍了分段错误 - 在 C 中声明和初始化数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我对 C 非常陌生.来自 Python、Java 和 C# 世界.这可能是一个愚蠢的问题,但我遇到了分段错误:
I am very new to C. coming from Python, Java and C# worlds. This might be a stupid question but I am getting segmentation fault:
// struct for storing matrices
typedef struct {
int m;
int n;
float* elts;
} Matrix;
在我的主要方法中:
Matrix A;
A.n = 3;
A.m = 3;
memcpy( A.elts, (float[]) {1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 7.0f, 8.0f, 9.0f}, 9 * sizeof(float)); // seg fault because of this memcpy.
我也试过没有 f
,同样的问题.可以帮忙吗
I also tried without the f
, same issue.Can you help please
推荐答案
你需要为 A.elts
分配内存来指向.您可以使用 malloc
来做到这一点.您正在做的是将您指定的常量数组处理到 elts
碰巧指向的任何地址(它未初始化).
You need to allocate memory for A.elts
to point to. You can do this with malloc
. What you are doing is coping the constant array you specified into whatever address elts
happens to point to (it is uninitialized).
您也可以将 A.elts
指向常量数组,如下所示:
You can also point A.elts
to the constant array like so:
float *myFloats = { 1.0f, 2.0f, 3.0f, 4.0f, 5.0f };
A.elts = myFloats;
这篇关于分段错误 - 在 C 中声明和初始化数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!