Mail Archives: djgpp/1997/02/24/18:36:56
Dim Zegebart wrote:
>
>
> I think, very symple code ;) (I never run it)
> So, my question is - may I use VLA this way : dynamicaly increase the
> array's size ?
>
> --
> Regards,
> Dim Zegebart,
> Moscow Russia.
Is this a special feature of djgpp? I've never seen anything like that.
Well, I have, but more later. Anyways, to do dynamic arrays in straight
C, you'd have to do something like:
int main(void)
{
int i;
int *arr;
/* Either initizlize to NULL, and use realloc every time,
or use malloc intially, and then realloc */
arr = NULL;
for (i=1;i<10;i++)
{
arr = realloc(arr, i * sizeof(int));
arr[i-1] = i;
}
}
Does this make sense? Realloc works like malloc, but copies the contents
of the first parameter over. --> WARNING: This is VERY slow!!!
Calling realloc like that is really slow. There is a better way to do
it,
which is to always double the size of the array. Doing so, one can prove
that insertion on the tail is still a constant time operation. But
writing
all of that would be stupid, since its been done:
#include <vector.h> /* Part of the Standard Template Library */
int main(void)
{
int i;
vector<int> arr;
/* No need to initialize a vector */
for (i=1;i<10;i++)
{
arr.push_back(i);
}
}
push_back places the element at the tail of the vector, and
automatically
allocates more memory as needed. And, vectors can still be accessed with
the [] notation. Example:
vector<int> A;
A.push_back(42);
cout << A[0] << endl; /* This prints 42 */
Hope this helps, and if anyone else has STL questions, I will try to
answer
them. (I have Prof. Musser for a class this semester, so I have a LOT of
contact/experience with it.)
Brian
- Raw text -