【发布时间】:2020-12-14 22:04:20
【问题描述】:
我正在尝试在 C 结构中创建两个动态分配的数组
typedef struct {
int count1;
int count2;
int *array1;
int *array2;
int check;
} __attribute__ ((packed)) test_T;
int main() {
int data[8] = { 2, 3, 20, 21, 30, 31, 32, 100 };
test_T *s_t = malloc(sizeof(s_t));
s_t->array1 = malloc(sizeof(int) * s_t->count1);
s_t->array2 = malloc(sizeof(int) * s_t->count2);
s_t = (test_T *)data;
printf("%d\n", s_t->check);
return 0;
}
array1 和 array2 的大小都是未知的,分别取决于 count1 和 count2。
我的结构数据定义在main 函数中,并将数据放入我的结构中。
问题是结构中的check 成员始终是32,但我希望这个值是100。
任何帮助表示赞赏。
【问题讨论】:
-
test_T *s_t = malloc(sizeof(s_t));-->test_T *s_t = malloc(sizeof(*s_t)); -
s_t = (test_T *)data;..那你为什么要malloc()? -
概念上的问题太多了......你能准确说出你想要实现的目标吗?似乎是 X-Y 问题。
-
你正在将数字转换为指针,sizeof(test_T) 绝对不是 8。
-
s_t = (test_T *)data;没有任何意义。请进一步澄清您的问题。
标签: arrays c memory dynamic malloc