[英]Dynamically changing the array size of an element of data structure in C
我是C编程新手。 如果这个问题不合适,请原谅。 我一直在努力动态地更改结构内部变量的大小(而不是结构本身)。 假设我有一个名为dist1的结构,如下面的代码。 我想将此结构传递给函数并动态更改test1的大小。 这有可能吗?
#include <stdio.h>
struct distance
{
double *test1;
double *test2;
};
int main()
{
struct distance dist1;
add(&dist1);
return 0;
}
void add(struct distance *d3)
{
// I want to dynamically change the size of "test1" to let's say test1(50)
// Is this possible?
}
这不可能以任何有意义的方式实现。 您总是可以使struct distance
容器的指针变为双精度而不是双精度,然后更改指向内存的大小,但是您的目标尚不清楚,因此我不确定该使用什么。
最好首先初始化struct distance
的成员。
struct distance dist1 = { NULL, NULL };
要更改分配的元素数,请使用realloc()
。 将其传递给d3->test1
和所需的字节数。 如果返回的值不为NULL
,则重新分配成功,并且代码应使用该值。 研究realloc()
以获得更多详细信息。
#include <stdlib.h>
void add(struct distance *d3) {
// I want to dynamically change the size of "test1" to let's say test1(50)
size_t new_element_count = 50;
void *tmp = realloc(d3->test1, sizeof *(d3->test1) * new_element_count);
if (tmp == NULL && new_element_count > 0) {
Handle_OutOfMemory();
} else {
d3->test1 = tmp;
}
}
我终于可以运行了。 我非常感谢大家的帮助和时间。 你们很棒!
#include <stdio.h>
#include <stdlib.h>
struct distance
{
double *test1;
double *test2;
};
void add(struct distance *dist1) ;
int main()
{
struct distance dist1;
dist1.test1 = (double *) malloc(5*sizeof(double));
dist1.test1[4] = 14.22;
printf("dist1.test1[4] from main() = %f\n", dist1.test1[4]);
add(&dist1);
printf("dist1.test2[3] from main() = %f\n", dist1.test2[3]);
return 0;
}
void add(struct distance *dist1)
{
printf("dist1.test1[4] from add() = %f\n", (*dist1).test1[4]);
(*dist1).test2 = (double *) malloc(10*sizeof(double));
(*dist1).test2[3] = 14.67;
printf("dist1.test2[3] from add() = %f\n", (*dist1).test2[3]);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.