so that the memory create itself its space for an array when required
How can i create dynamic array in C and VB?
Since you mentioned VB, I'll guess that you mean Visual C++?
If so, there's a CArray template object that you can use, and there are already sub-classes of it, such as CByteArray, CDWordArray, CObArray, CPtrArray, CStringArray, CUIntArray, and CWordArray,
You can do something like this:
CStringArray myStrArray;
myStrArray.Add("A new string");
myStrArray.Add("Another new string");
printf("%d", myStrArray.GetSize()); // This would print 2 at this point
printf("%s", (char *)myStrArray[1]); // This would print "Another new String" without the quotes
myStrArray.RemoveAll(); // This empties the array
Reply:You cannot create a dynamic array in C but you can write code to enlarge and shrink one as needed or you could just use linked lists which would be quicker.
for instatance
int *myarray = NULL;
mycount = 0;
increase (%26amp;myarray, %26amp;mycount);
myarray[0] = 5;
decrease(myarray, %26amp;mycount);
The routines are
void increase(int **myarray, int *mycount) {
int n;
*mycount++;
int *newarray = malloc(*mycount, sizeof(int));
for (n=0; n%26lt;(*mycount - 1); n++) {
newarray[n] = *myarray[n];
}
free(*myarray);
*myarray = newarray;
}
(something like that anyway)
Not tested!
The other routine would be something similar.
Reply:IN VB you declare a dynamic array by naming a variable with parenthesis. A static array, one with a fixed number of elements is declared by placing an integer within the parenthesis.
dim myStaticArray(50) as string
dim myDynamicArray() as string
to use the dynamic array you my dimension it prior to using it in code, The computer still needs to allocate memory for it, with a dynamic array you are performing the allocation at run time vs design time.
Use the REDIM command to allocate memory and size the number of elements
REDIM myDynamicArray(25)
Depending on how you use the array in your program you may need to resize the array. You may simply REDIM the array again to what ever size you need. However in doing so the contents of the array will be erased.
If you need to resize the array and Key any data already assigned to it you use the PRESERVE modifier.
REDIM PRESERVE myDynamicArray(50)
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment