English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

so that the memory create itself its space for an array when required

2007-06-08 01:34:15 · 3 answers · asked by rajesh marndi 1 in Computers & Internet Programming & Design

3 answers

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

2007-06-08 07:13:09 · answer #1 · answered by Chris C 7 · 0 0

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)

2007-06-08 02:37:22 · answer #2 · answered by MarkG 7 · 1 0

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 (&myarray, &mycount);
myarray[0] = 5;
decrease(myarray, &mycount);

The routines are
void increase(int **myarray, int *mycount) {
int n;
*mycount++;
int *newarray = malloc(*mycount, sizeof(int));
for (n=0; n<(*mycount - 1); n++) {
newarray[n] = *myarray[n];
}
free(*myarray);
*myarray = newarray;
}

(something like that anyway)
Not tested!
The other routine would be something similar.

2007-06-08 03:08:14 · answer #3 · answered by Anonymous · 0 0

fedest.com, questions and answers