the book i began reading taught me to use char* variable; to store strings, this may not be what i'm looking for... if i'm not mistaken when i tried char * ss=new char[]; it didn't work the way a normal pointer did, i'm using dev c++ now, and i need to find another way to do what i'm doing. The segmentation fault is marked with comments, at least that's the point debug told me a segmentation fault occurred...
#ifndef __unix__
#include <cstdlib>
#include <iostream>
#include <fstream>
usingnamespace std;
char*strung;
char*big(char*);
char*ar1(char*);
/* return 1 = usage */
/* return 2 = didn't make the file */
int n=1;
char* big(char*oneatatime)
{
char * store=NULL;
strcat(store," ");
strcat(store,oneatatime);
return store; // ACCESS VIOLATION OCCURRED SOMETIME AROUND HERE
}
char * ar1(char*add_once)
{
char* temp;
temp=add_once;
// strcat(temp," ");
return temp;
}
int main(int argc, char *argv[])
{ // MAIN
ofstream doc;
switch(argc)
{
case 1:
cout << "USAGE: np <filename>\n";
return 1;
case 2:
doc.open(argv[1],ios::out);
if(doc.is_open())
{
cout << "FILE OPENED SUCCESSFULLY";
doc.close();
return 0;
}
else{
cout << "FILE WAS NOT MADE.";
return 2;
}
#ifdef TESTING
default:
cout << "SEE MANUAL";
return 5;
}
#endif
default:
strung=NULL;
/* functions used to make up for my diminished
mental capacity */
strung=ar1(argv[1]);
for(int n=2;n!=argc;n++)
{
strcat(strung,big(argv[n]));
}
/* AT THIS POINT I THINK WE HAVE A NICE STRING FILLED WITH EVERYTHING YOU TYPED
ON THE CONSOLE AFTER "NP" LIKE SAY... "NP BILL GATES"
STRING CONTAINS BILL GATES
*/
if(!(strlen(strung))>255)
{ //if strung>255
doc.open(strung,ios::out);
/* NESTING IF TO CHECK IF OPEN */
if(doc.is_open())
{ //
cout << "DOCUMENT CREATION SUCCESS";
doc.close();
return 0;
} //
else{ //just to make sure this else is for the nested if, right?
cout << "DOCUMENT CREATION FAILED.";
return 2;
} // } //UNKNOWN
} //if strung>255
} // switch closing brace
return 0; // this shouldn't get executed
} //main closing brace
#endif
I know someone else's code can get pretty horrible to look through sometimes, but, any help would be appreciated, please direct me toward a better programming style and such.
of course the access violation occurred when using more than 1 argument.
If you want to return a char *, there are no other alternatives. And don't forget to initialize the array to zero (or at least the first element) before calling strcat().
I mean *store=0; or store[0]=0;
strcat() assumes that the first parameter is a valid C-string, and begins copying the second parameter at strlen(str1).
std::string is the other alternative. I see that you are including C++ headers so why bother using char* at all? Any time that you declare a pointer you have to have a plan for filling the pointer with an address to allocated memory or allocate the memory yourself. You can never pass a null or uninitialized pointer to a c-run time function.