段错误 - 声明和init数组用C [英] Segmentation Fault - declare and init array in C
本文介绍了段错误 - 声明和init数组用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;
在我的主要方法:
and in my main method:
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
做到这一点。你所要做的是应对你成任何地址指定的常量数组的ELT
恰好指向(这是未初始化)。
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;
这篇关于段错误 - 声明和init数组用C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文