Mail Archives: djgpp/1999/09/02/12:41:05

From: horst DOT kraemer AT snafu DOT de (Horst Kraemer)
Newsgroups: comp.os.msdos.djgpp
Subject: Re: How to make allocate an array of strings?
Date: Thu, 02 Sep 1999 12:36:00 GMT
Organization: [Posted via] Interactive Networx
Lines: 97
Message-ID: <>
References: <199909020524 DOT BAA21825 AT delorie DOT com>
X-Newsreader: Forte Free Agent 1.11/32.235
To: djgpp AT delorie DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp
Reply-To: djgpp AT delorie DOT com

On Thu, 2 Sep 1999 04:32:54 -0700, "Dan Gold" <TedMat AT CoastNet DOT com>

> Okay this is a stupid newbie question but I never actually learned how it
> was done, mayby better suited for a C programming group but I want to
> allocate an array of strings.  I understand how to use strings but not
> create them and not multi-dimensional strings.  Could someone please give
> me an example, the array will hold a list of filenames?  
> // one dimensional
> char * string = (char *)malloc(string_size * sizeof(char));


	char * string = new char[string_size]; /* C++ */
        delete [] string;

	char * string = malloc(string_size); /* C */

(sizeof (char) is 1 by definition).

You would only need a cast (char*)malloc if you compile the C code
with a C++ compiler which is abomination ;-) Don't mix languages.

> // two dimensional
>            ?? 

This can be interpreted in various ways. You may either want an array
of strings where you allocate the same amount of memory for every
string and in the latter case you may know the common size of the
strings at compile time - or you may not.

Let's step up from the constant case to the variable case


This would be an equivalent to a static array

	char a[number][SIZE];

A string would be addressed by a[i].

    char (*p)[SIZE] = new char[number][SIZE]; // C++

    char (*p)[SIZE] = malloc(number*SIZE); /* C */

'number' may be a variable. SIZE has to be a litteral or #defined
constant or may be something like

	const int SIZE=80;

in C++.

The string would be addressed by p[i].

If you don't want to allocate the same size for every string or if the
size is not known at compile time and introduced by a variable, you
have to use an array of pointers to char instead of an array of arrays
of char.

	char ** p = new char*[number];

Now for every i from 0 to number-1 you may assign a different size

	p[i] = new char[size_for_string_i];


	for (i=0;i<number;++i) delete [] p[i];
	delete [] p;

in C

	char ** p = malloc [number * sizeof (char*) ];
	char ** p = malloc [number * sizeof *p];

	p[i] = malloc(size_for_string_i);


	for (i=0;i<number;++i) free(p[i]);

In this case, too, a specific string would be addressed by p[i]
although the underlying "physical" data structure is completely
different. That's one of the miracles of C ;-)


- Raw text -

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