Dynamic Memory and Variable type.

Jun 25, 2008 at 9:42am
Is there a way in which you can assign a type of variable e.g. int, float, short etc. AFTER a user input?

I thought this could be useful in saving memory, for example, where you may create a double, and the user types a number which could be small enough to be placed into an integer variable. I wondered if this could be something to do with Dynamic Memory Allocation?

Thanks in advance.
Jun 25, 2008 at 6:42pm
Yes you can. And yes it would be dynamic memory allocation. But the amount of memory saved would be very very tiny. If any at all.

For example
int myInt = 1234;
Typically an int is 4 bytes. So 'myInt' would need 4 bytes of storage. To have different possible types of storage you'd probably want to use a Union. A Union can be created dynamically, but requires the amount of memory as the biggest type you are storing (double = 8 bytes).

So, You union would be 8 Bytes + 1 Byte for the Address of the pointer. So 9 bytes in total. You've more than doubled your memory footprint =\

Not to mention, speed would be slowly because you'd have to make calls to a separate memory location on the heap as opposed to the stack.

I hope this helps :)
Jun 26, 2008 at 8:54am
thankyou for your reply, I thought about your unions and I now understand what you mean about the memory footprint doubling. what would be the best course of action on saving memory then? say if i machine was ver low end hardware. would i have to revert to some other language which is more efficient, or is there common practice techniques in making a very efficient program?
Jun 26, 2008 at 10:16am
That depends on how tight your memory is. Sometimes assembler can save space but at the cost of development time. Usually there will be a C compiler that will be good enough to make it not worth doing that.

Saving memory is just common sense really. Only use what you need. If you need to pass lots of parameters to a function, put them in a structure and pass a pointer to it. This will reduce the amount of memory the call stack uses. Don't use large arrays for text when it's only for one word. Like I said common sense. Switching between ints, chars and shorts does save much unless you are using lots of them.

Hope this helps
Topic archived. No new replies allowed.