[英]How to fill an array of structs when parameter argument is a double pointer
Working on a piece of homework, having issue with filling in a struct array with values as I keep getting a "Invalid write of size 8" error after I fill anything past the first element.在做作业时,在用值填充结构数组时遇到问题,因为在填充第一个元素之后的任何内容后,我不断收到“大小 8 的无效写入”错误。
#include <stdio.h>
#include <stdlib.h>
struct DS_t {
int a;
double b;
char c;
};
void f4(struct DS_t ** x) {
*x = (struct DS_t *) malloc(4 * sizeof(struct DS_t));
struct DS_t d1 = {3, 2.3};
*x[0] = d1;
*x[1] = d1;
}
int main() {
struct DS_t * ds4_p;
f4( &ds4_p );
printf("DS_t[0] = {%d, %f, %s}\n", ds4_p[0].a, ds4_p[0].b, ds4_p[0].c);
printf("DS_t[1] = {%d, %f, %s}\n", ds4_p[1].a, ds4_p[1].b, ds4_p[1].c);
printf("DS_t[2] = {%d, %f, %s}\n", ds4_p[2].a, ds4_p[2].b, ds4_p[2].c);
//etc
}
I want to create an array of struct DS_t using the *x to the **x in the function parameter and then fill up that array, which I believe *x = (struct DS_t *)calloc(4, sizeof(struct DS_t));我想使用 function 参数中的 *x 到 **x 创建一个 struct DS_t 数组,然后填充该数组,我相信 *x = (struct DS_t *)calloc(4, sizeof(struct DS_t)) ; does.
做。 Seeing it through a visualizer, I see that in f4, the x points to ds4_p and then ds4_p points to 4 struct DS_t, which is what I want.
通过可视化工具查看,我看到在 f4 中,x 指向 ds4_p,然后 ds4_p 指向 4 struct DS_t,这就是我想要的。
But whenever I go to try and fill it, I get that invalid write of size 8 error.但是每当我 go 尝试填充它时,我都会收到大小为 8 的无效写入错误。 I have no problem with *x[0]= d1, it fills the first element just fine, anything after is where my issue lies.
我对 *x[0]= d1 没有问题,它很好地填充了第一个元素,之后的任何内容都是我的问题所在。
What is it that I am missing with this?我错过了什么? Been working on it for a while and haven't had any luck with it.
已经研究了一段时间,但没有任何运气。 Maybe I'm going about it the wrong way?
也许我会以错误的方式去做? Just need to print out each element of the array pointer.
只需要打印出数组指针的每个元素即可。 The struct and function was all created specifically like this, so can't change any of that.
struct 和 function 都是这样专门创建的,所以不能更改任何一个。
A number of problems in the code:代码中的一些问题:
[]
has higher order of precedence than *
. []
的优先级高于*
。 So *x[0] = d1;
*x[0] = d1;
is actually equivalent to *(x[0]) = d1;
*(x[0]) = d1;
. (*x)[0] = d1;
(*x)[0] = d1;
. malloc
rather than calloc
as you claim.malloc
而不是您声称的calloc
。 Which means ds4_p[2]
(and ds4_p[3]
) are uninitalised.ds4_p[2]
(和ds4_p[3]
)未初始化。 Either use calloc
or don't attempt to access ds4_p[2]
.calloc
或不要尝试访问ds4_p[2]
。%s
is for strings. %s
用于字符串。 But you only have a single char
.char
。 Use %c
instead.%c
。 But note that d1.c
is set to 0
so %c
will not print any visible character.d1.c
设置为0
,因此%c
不会打印任何可见字符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.