[英]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.