访问和设置结构中的数组值
我有一个像这样的结构:
typedef struct {
int sizes[3];
float **vals[3]; // an array of size 3 of float ** pointers
} mystruct;
我想要做的是在一个函数中设置这些数组值,该函数采用指向 mystruct
的指针。
void populateStruct(mystruct *s) {
int i, j, n;
for (n = 0; n < 3; n++) {
scanf("%d", &s->sizes[n]);
// Malloc the float pointers (**vals) based on the scanned sizes
s->vals[n] = (float **)malloc(s->sizes[n] * sizeof(float *));
for (i = 0; i < s->sizes[n]; i++)
s->vals[n][i] = (float *)malloc(s->sizes[n] * sizeof(float));
// Populate the float "arrays"
for (i = 0; i < s->sizes[n]; i++) {
for (j = 0; j < s->sizes[n]; j++) {
scanf("%f", &s->vals[n][i][j]);
}
}
}
}
以下是我在 main
中使用该函数的方式:
int main() {
mystruct *s1;
populateStructure(s1);
return 0;
}
此代码可以正常编译,但在运行时出现段错误。 C不是我的强项,所以我不太确定我做错了什么。
I have a struct like this:
typedef struct {
int sizes[3];
float **vals[3]; // an array of size 3 of float ** pointers
} mystruct;
What I'm trying to do is set these array values in a function that takes a pointer to a mystruct
.
void populateStruct(mystruct *s) {
int i, j, n;
for (n = 0; n < 3; n++) {
scanf("%d", &s->sizes[n]);
// Malloc the float pointers (**vals) based on the scanned sizes
s->vals[n] = (float **)malloc(s->sizes[n] * sizeof(float *));
for (i = 0; i < s->sizes[n]; i++)
s->vals[n][i] = (float *)malloc(s->sizes[n] * sizeof(float));
// Populate the float "arrays"
for (i = 0; i < s->sizes[n]; i++) {
for (j = 0; j < s->sizes[n]; j++) {
scanf("%f", &s->vals[n][i][j]);
}
}
}
}
Here is how I'm using the function in main
:
int main() {
mystruct *s1;
populateStructure(s1);
return 0;
}
This code compiles fine, but I get a seg fault when I run it. C is not a strong point of mine, so I'm not too sure what I'm doing wrong.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您如何声明您的结构以及如何传递它?
在调用 populateStruct 的函数中,您可能应该将 s: 声明
为 mystruct 并调用 populateStruct(&s)
或
How are you declaring your s structure and how are you passing it?
In your function where you call populateStruct you should probably declare s:
as
mystruct s and call populateStruct(&s)
or
s1只是一个具有不可预测值的指针。您没有为所需的结构分配内存。
取消引用野生(未初始化)指针会导致 segv。
您可以将代码修改为:
或
(不要忘记在第二个代码中释放 s1)
s1 is only a pointer with unpredictable value. You didn't allocate memory for the struct you need.
Dereferencing a wild (uninitialized) pointer would cause segv.
You can modify your code to either:
or
( don't forget to free s1 in the second one)