• Open Menu Close Menu
  • Apple
  • Shopping Bag
  • Apple
  • Mac
  • iPad
  • iPhone
  • Watch
  • TV
  • Music
  • Support
  • Search apple.com
  • Shopping Bag

Lists

Open Menu Close Menu
  • Terms and Conditions
  • Lists hosted on this site
  • Email the Postmaster
  • Tips for posting to public mailing lists
Re: [OT] An array of C-Strings
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [OT] An array of C-Strings


  • Subject: Re: [OT] An array of C-Strings
  • From: Brian Luft <email@hidden>
  • Date: Sat, 26 Jan 2002 22:40:19 -0600

On 1/26/02 10:22 PM, "Sam Goldman" <email@hidden> wrote:

> Sorry for being off topic, but I don't have a C++ book yet
> (recommendations?) and I need a pretty simple question answered.
>
> I want to have an array of C-Strings (which as you know are arrays
> themselves). The C-Strings in the array would be added at runtime and I
> don't know how many there will be or how long each one will be.
>
> Here's what I have come up with so far.
>
> #include <iostream.h>
>
> int main()
> {
> char **days;
> char *word = "The length of the word would be variable";
> int i;
>
> for (i = 0; i < 7; i++)
> {
> days[i] = word;
> }
> for (i = 0; i < 7; i++)
> {
> cout << days[i] << endl;
> }
>
> return 0;
> }
>
> It compiles with gcc, but during runtime it quits with a Bus Error message.

Bad! Very bad!
No where in there did you ever allocate any memory for that array, so just
writing to indices into it are clobbering memory you don't own. The SIGBUS
is caused because you wrote into memory you don't own.

If you don't mind using STL, the nicest way I know of doing it is the
following:

#include <vector>
#include <iostream>

int main(void)
{
std::vector <char *> days;

for(int i = 0; i < 7; i++)
{
days.push_back(word);
}

for(int i = 0; i < days.size(); i++)
{
cout << days[i] << endl;
}

return(0);
}

It's not so nice if you don't want to use STL.

Hope that helps. Brian

--
Brian Luft
email@hidden
http://youma.cjb.net


  • Follow-Ups:
    • Re: [OT] An array of C-Strings
      • From: Sam Goldman <email@hidden>
References: 
 >[OT] An array of C-Strings (From: Sam Goldman <email@hidden>)

  • Prev by Date: Re: [OT] An array of C-Strings
  • Next by Date: Re: [OT] An array of C-Strings
  • Previous by thread: Re: [OT] An array of C-Strings
  • Next by thread: Re: [OT] An array of C-Strings
  • Index(es):
    • Date
    • Thread