Article View: gnu.g++.help
Article #932Re: Why not? c++ Array of strings...
From: Caius Martius
Date: Tue, 19 Mar 1996 00:10
Date: Tue, 19 Mar 1996 00:10
93 lines
3133 bytes
3133 bytes
Arthur Cinader Jr wrote:
>
> Note Followup
>
> I want a class to a have a member that is an array of
> character strings that are dynamically allocated. I have written
> a very simple program that shows the eveolution of my thought
> that leads me to beleieve that I should be able to do what I
> am trying, but I get a segmentation fault and core dump when I
> try it. Why? I obviously am missing something. I have kept
> the code as brief as possible (I'm using g++ v2.4):
>
> ***foo.h
> class Foo {
> public:
> Foo(); // constructor
> ~Foo(); // destructor
> private:
> char a[10]; // declare and define an array of characters
> char *b; // declare a string pointer
> char *c[10]; // declare an array of ten strings?
> };
>
> ***foo.C
> nclude <iostream.h>
> #include <assert.h>
> #include <string.h>
> #include "foo.h"
>
> // Constructor -- all the action is here --
> Foo::Foo()
> {
> // populate the character array
> a[0] = 'a';
> a[1] = 'r';
> a[2] = 't';
> a[3] = 'h';
> a[4] = 'u';
> a[5] = 'r';
>
> // print the character array
> cout << "output from array of char: ";
> for(int i = 0 ; i < 6 ; i++)
> cout << a[i];
>
> cout << endl;
>
> // populate the string
> b = new char[7]; // allocate space
> assert( b != 0); // make sure space was allocated
> strcpy(b, "arthur");
>
> // print the string
> cout << "output from *char: " << b;
>
> cout << endl;
>
> // So far so good. This is where it all falls apart
> // populate array of strings
> c[0] = new char[10]; // allocate space
> assert(c[0] != 0); // make sure space was allocated
> strcpy(c[0], "arthur");
> c[1] = new char[10];
> assert(c[1] != 0);
> strcpy(c[1], "cinader");
> c[2] = new char[10];
> assert(c[2] != 0);
> strcpy(c[2], "jr.");
>
> // output array of strings
> for (i = 0 ; i < 3 ; i--) // *** This should be unary increment. ++ ***
> cout << c[i] << " ";
>
> cout << endl;
>
> }
>
> Foo::~Foo() {
> // clean up the mess
> delete [] b;
> for(int i = 0; i < 3; i --) // *** This should be unary increment. ++ ***
> delete [] c[i];
> }
>
> **** foo.driver.C
> #include "foo.h"
>
> main()
> {
> Foo f;
>
> return 0;
> }
Technical Details
Message-ID:
<314DFB63.581C@nando.net>Path:
arc1-ca.pugleaf.net!castle.nando.net!newsReferences:
<4ii3pp$4df@panix.com>Show Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!castle.nando.net!news From: Caius Martius <caius@nando.net> Newsgroups: gnu.g++.help,comp.lang.c++ Subject: Re: Why not? c++ Array of strings... Date: Mon, 18 Mar 1996 16:10:11 -0800 Organization: Nando.net Message-ID: <314DFB63.581C@nando.net> References: <4ii3pp$4df@panix.com> NNTP-Posting-Host: grail509.nando.net Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Transfer-Encoding: 7bit X-Mailer: Mozilla 2.0 (Win95; I; 16bit)