Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

More bytes allocated to a variable in C++?

Name: Ekce 2006-01-28 18:33

Hey, I started programming in C++, and I was wondering if there was a way to assign a variable X amount of bytes. 8 bytes is just not enough. I will mainly be using integers.

Name: Anonymous 2006-01-29 14:13

>>4
I'm not quite sure how it works out for an integer
You can have an array of integers, like:
int i[100]
You now have 100 ints, accessible through i[0], i[1], ... i[99]. Also, *i is i[0], and *(i + n) is i[n] .

Suppose I want to give an integer variable 128 BYTES
If you really need to work with 1024 bit single integers (i.e. all at once), you should look for an arbitrarily large integers library. LCC-Win32 comes with one called bignums, for example, although LCC is a C++-- compiler only (not C++). In most machines/compilers, native integer types are char (8 bits), short (16 bits), long (32 bits) and long long (64 bits).

I was also thinking about giving up on variables and using several files for input and output, but that would be very memory intensive, and I don't want to abuse my hard drive.
Anything is memory-intensive, unless you mean your hard drive. If that's the case, your OS will cache them, so you won't be really using the hard drive too much, just an inefficient way to use memory.

I haven't heard much about malloc, and I can't seem to find the function in my textbook, so any information really helps.
malloc(size) returns a pointer to a newly allocated memory block which you can use for anything you want. You must assign malloc's result to a pointer variable of the type you want to work with. For example, let's suppose you read from a file a number stored in variable v, and then you need to process v 32 bit integers, and you don't know v until runtime. You'll need to do something like:
void Process(long v) { //Our function to process v elements
    long *p; //Create a pointer to long
    p = malloc(v * sizeof(long)) //Request memory for v times a long
Now you have p, a pointer to a newly allocated block of memory to store v longs. You can use it just like an array: p[0] is the first one, p[v-1] is the last one. After using malloc, and before exiting your function, you have to free the memory block you requested with free(p) .

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List