Click to See Complete Forum and Search --> : why the following code using char* doesn't work?
indiocolifa
December 31st, 2002, 12:26 PM
why the following code doesn't work (gives me a general protection fault):
int MAX = 200;
char *optiondesc[MAX];
int main()
{
...
// get maximum number of options
do
{
cout << "Enter the number of options you want to evaluate:" << endl
<< "(minimum is 2)" << endl;
cout << "?";
cin >> numopt;
} while (numopt < 2);
for (i=0; i < numopt; i++)
{
cout << "Option " << i << "?";
cin >> optiondesc[i];
}
...
return 0;
}
May be I've not allocated spacE?:confused:
vinodp
December 31st, 2002, 01:31 PM
May be I've not allocated spacE?
-----------------------------------------------------------
YES ur right u have not allocated the space for char*
try something like this
for (i=0; i <MAX ; i++)
{
optiondesc[i]=(char*)malloc(size);
}
Vinod
stober
January 1st, 2003, 09:49 AM
since you are using C++, why not use the vector and get rid of the malloc() stuff
#pragma warning(disable : 4786)
#include <stdio.h>
#include <string>
#include <vector>
#include <iostream>
using namespace std;
vector<string> optiondesc;
int main()
{
// get maximum number of options
string option;
int numopt, i;
do
{
cout << "Enter the number of options you want to evaluate:" << endl
<< "(minimum is 2)" << endl;
cout << "?";
cin >> numopt;
} while (numopt < 2);
for (i=0; i < numopt; i++)
{
cout << "Option " << i << "?";
cin >> option;
optiondesc.push_back(option);
}
return 0;
}
Cheesus
January 2nd, 2003, 09:30 AM
The real reason your original code didn't work was in the declaration of 'optiondesc'.
By declaring it as:
char *optiondesc[MAX];
you are saying you want and array of MAX elements where each element is of type char*.
That's why you need to inialise each element to point to some memory.
This could also have been done as:
char optiondesc[MAX][256];
(note the abscence of the * in the declaration!)
Where each element would have been statically allocated 256 bytes.
While this is legitimate I totally agree with the other guys responses, but just thought someone should clear it up for you as to why your original code didn't work.
codeguru.com
Copyright Internet.com Inc., All Rights Reserved.