-
Initialize an array
Will the code below preload an array of 100 locations with the
value 10000?
size - 100
int memory[Size]
const int mem = 10000;
int *p, memory[Size];
for ( p = &memory[0]; p < &memory[Size]; *p++ )
*p++ = mem;
Please advise if there is a better way. It is an exercise that should use pointers.
Thanks
-
memset(pointer,defaultvalue,numobjects*sizeof(obje ct))
unsigned char *Screen=new unsigned char[64000];
memset(Screen,0,64000);
unsigned int *Screen=new unsigned int[64000];
memset(Screen,0,(64000<<1)); //or 64000*sizeof(int)
Top example unsigned char is 1 byte. Bottom example - in 16 bit real mode programming an integer is 2 bytes so you must multiply 64000 by 2, or shift left by 1, to get the correct size of the memory. 64000 integers requires 128000 bytes since each integer is 2 bytes or 16 bits.
Only use a for loop when you are initializing an array with different default values since this cannot be done using memset or other fast memory functions or w/o using assembly.
-
That was posted by Bubba. Argghhhhhh!!!
Keep deleting my cookies and forgetting to sign in.
-
Bubba:
Thanks for the reply. However, you blew past me. I'm not sure if I understand what you said.
Your example did not refernce the value 10000 or the array memory[Size]. Sorry for the confusion.
This is an initialization problem. Once the memory is filled. The program changes specific values as required.
Thanks
Cheesehead.
-
Never mind, I did some testing and the results were not what I expected. My init only works for character arrays since memset works with bytes and the max value you can use is 255. If you were to memset an integer array with 255, all the values in the array would be 65535 - not what you want. It would place 255 high and low in each element of the array since it operates on bytes only.
Looks like you are stuck with a for loop unless you know assembly language.
-
Thanks for the try.
Does that mean that the for loop in the original post will work?
-
Don't think so. Try this instead:
const int Size = 100;
int memory[Size];
const int mem = 10000;
int *p;
for ( p = &memory[0]; p < p + Size; p++ )
*p++ = mem;
this loop says start at the memory site for the first element of the array of int called memory. As long as the address in p is less than the initial address site plus the the amount of memory necessary for the number of elements in memory[], place the value of mem in the appropriate spot in memory, and increment p by the size of one int.