问题描述
您好,
这是Raghu。我在声明一个结构时遇到了问题。
考虑
struct hai {
int id;
char sex ;
int age;
};
这里当一个变量被用于这个结构然后立即
for所有成员的内存都已分配。但是,只有当性别为M而内存不应该分配时,我需要为
年龄分配内存。
认为您理解查询。
并等待你的回复
再见小心
带笑容
Raghu
Hello ,
This is Raghu. I have a problem in declaring a structure.
Consider
struct hai{
int id;
char sex;
int age;
};
here when a variable is instianted for this structure then immediately
for all members memory is allocated. But I need to allocate memory for
age only if sex is M else the memory should not allocate.
Think you understand the query.
and awaiting for your reply
bye take care
with smile
Raghu
推荐答案
然后你不能使用这样的结构 - 一个结构_is_
组件的组合以及你有编译器的时候创建一个新的
结构实例,它将为你的所有
成员提供内存。唯一的出路是在结构中有一个指针
,你只能在某些条件下手动分配内存,
喜欢(缺少必要的错误检查):
struct hai2 {
int id;
char sex;
int * age;
}人;
/ *在这里为person.sex分配一些值* /
if(person.sex ==''M''){
person.age = malloc(sizeof * person.age);
* person.age = 17;
}
当然,你还需要在结构超出范围之前解除内存的释放。
Obvioulsy,这个例子看起来很愚蠢(int指针可能
至少需要一个整数的内存),但有几个
这种方法很有意义的情况。
问候,Jens
-
\ Jens Thoms Toerring ___
\ __________________________
我想你可以做这样的事情(
简称省略错误处理): -
char sex;
int age;
struct hai * hp;
....
<处理以获取数据>
....
if(sex ==''M''){
hp = malloc(sizeof(struct hai));
hp-> id =< whatever> ;;
hp-> sex =性别;
hp->年龄=年龄;
}其他{/ *我认为你已经确认性别是M或F ''* /
hp = malloc(sizeof(struct hai) - sizeof(int));
hp-> id =< whatever> ;;
hp-> sex = sex;
}
它很丑陋,几乎可以保证在以后会让你感到悲伤,但是
它(在某种意义上)符合您的要求。
但是,您的要求是无稽之谈。每个节省1个机器字
" struct hai"不值得打扰,除非你非常
b $ b内存受限,IMNSHO ...
I suppose you could do something like this (error handling omitted for
brevity) :-
char sex;
int age;
struct hai *hp;
....
<processing to get the data to work with>
....
if (sex == ''M'') {
hp = malloc(sizeof(struct hai));
hp->id = <whatever>;
hp->sex = sex;
hp->age = age;
} else { /* I assume you''ve validate that sex is ''M'' or ''F'' */
hp = malloc(sizeof(struct hai) - sizeof(int));
hp->id = <whatever>;
hp->sex = sex;
}
It''s ugly and almost guaranteed to cause you grief in later times, but
it does (in some sense) meet your requirement.
However, your requirement is nonsense. Saving 1 machine word per
"struct hai" is not worth bothering with unless you are hugely
memory-constrained, IMNSHO...
正如Jens指出的,如果还有更多而不仅仅是一个单词,例如一个嵌套结构,其存在与否取决于结构中的其他数据,那么基于指针的解决方案可能适用
...
As Jens points out, if there is more than just a single word, such as a
nested structure, the presence or absence of which is dependant on
other data in the structure, then a pointer-based solution may be
appropriate...
这篇关于如何动态地为成员分配内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!