delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1997/02/24/18:36:56

From: Brian Osman <osmanb AT rpi DOT edu>
Newsgroups: comp.os.msdos.djgpp
Subject: Re: Variable length array ?
Date: Wed, 19 Feb 1997 13:44:29 -0500
Organization: Rensselaer Polytechnic Institute, Troy NY, USA
Lines: 67
Message-ID: <330B4A0D.7231@rpi.edu>
References: <330B9EDB DOT 79D7 AT post DOT comstar DOT ru>
Reply-To: osmanb AT rpi DOT edu
NNTP-Posting-Host: darkwing.stu.rpi.edu
Mime-Version: 1.0
To: djgpp AT delorie DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp

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 -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019