delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1997/10/18/16:45:54

From: mert0407 AT sable DOT ox DOT ac DOT uk (George Foot)
Newsgroups: comp.os.msdos.djgpp
Subject: Re: Function that takes an array of strings (2D array) : HOW?
Date: 18 Oct 1997 16:52:09 GMT
Organization: Oxford University, England
Message-ID: <62apfp$jqo$2@news.ox.ac.uk>
References: <62ao6b$nh8$3 AT news DOT interlog DOT com>
NNTP-Posting-Host: sable.ox.ac.uk
Lines: 56
To: djgpp AT delorie DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp

On Sat, 18 Oct 97 16:38:02 GMT in comp.os.msdos.djgpp Gautam N. Lad
(gautam AT interlog DOT com) wrote: 

: 	void MyFunc(int n, char **Text); // First arguement is # of items

That's fine, much like: int main (int argc, char **argv)

: And I use variables like this:
: 	char **mybuf;
: 	int c;

: 	*mybuf=new char[100]; // create 100 elements
: 	for(c=0;c<100;c++)	// Fill up the array 'mybuf'
: 	  sprintf(mybuf[x],"Number %d",x);
                        ^--------------^----- (I think you mean `c')

You need to do something more like this (C version):

mybuf = (char **) malloc (100 * sizeof (char *));
for (c=0; c<100; c++) {
 mybuf[c] = (char *) malloc (size_of_each_string);
 sprintf (mybuf[c], "Number %d", c);
}

Note that first you need to allocate enough space to hold 100 `char *'
items, and then you need to allocate some space for each of them to point
to, before putting the string into it. You could use strdup to do the
latter two stages both together.

Incidentally, the convention with the main function's argc and argv values
is that argc is the number of parameters, and argv is an array of pointers
one larger than argc says, with the last being NULL; i.e. argv[argc] ==
NULL. E.g. if you type:

foo 1 2 3

then argc = 4 and argv = { "foo", "1", "2", "3", NULL }. This means that
argc is somewhat redundant, and in some circumstances it's more convenient
to just check for the NULL pointer at the end of argv, rather than run a
count up to argc. You may or may not want to work your function this way,
though.

I don't use the new operator personally (it's C++), but AFAIK it would go
something like this:

mybuf = new char* [100];
for (...) {
 mybuf[c] = new char [size_of_each_string];
 ...
}

... but take that with a pinch of salt.

-- 
George Foot <mert0407 AT sable DOT ox DOT ac DOT uk>
Merton College, Oxford

- Raw text -


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