I am in the progress of trying to write a C++ (Visual C++ compile) program that dynamically reads in files from a series of sub directories that the user inputs. I am trying to catenate several strings together to prevent to many input request from the user. I could probably use the strcat function at this point and get the desired result, but at this point I really just want to know why my custom function isn't working. Below as recommended is a test program I wrote to help assess the situation, but this is just one of the many variations I have tried. The problem is besides giving me an error it does all the output, but it never gives me the desired result for output (C:\somedirectory\content\). I'm a newb with c++ and even more with using pointers in c++ so any input on the subject would be appreciated.
No Debug
ERROR: Run-Time Check Failure #2 - Stack around the variable 'adir' was corrupted.
during Debug
ERROR: Run-Time Check Failure #2 - Stack around the variable 'sub' was corrupted.
// function call in main
len = cat(&dir,&adir,&subdir);
int cat(char **lawl, char **catftw, char **sub)
{
int lens,lenm,tlen,x;
for(x=0;catftw[x]!=0;x++);
lenm = x;
for(x=0;sub[x]!=0;x++);
lens = x;
tlen = lenm + lens;
*lawl = new char[tlen];
for(x=0;x<lenm;x++)
{
lawl[x] = catftw[x];
}
for(x=lenm;x<tlen;x++)
{
lawl[x] = sub[x - lenm];
}
return tlen;
}
The whole test program including output for testing
#include<iostream>
using namespace std;
int cat(char **lawl, char **catftw, char **sub);
int main()
{
char *adir = {"C:\\somedirectory\\"}, *subdir = {"content\\"}, *dir; int len;// pretty sure these char values are not initialized correctly
cout << adir << endl << subdir << endl;
len = cat(&dir,&adir,&subdir); // when properly initialized and passed no error in build but stops fails after getting lenths
cout << len << endl << dir << endl;
return 0;
}
int cat(char **lawl, char **catftw, char **sub)
{
int lens,lenm,tlen,x; //Counters are giving wrong variables when initialized value as pointer but program runs further
for(x=0;catftw[x]!=0;x++);
lenm = x;
cout << lenm << endl;
for(x=0;sub[x]!=0;x++);
lens = x;
cout << lens << endl;
tlen = lenm + lens;
cout << tlen << endl;
*lawl = new char[tlen];
for(x=0;x<lenm;x++) //possibly writing null character
{
lawl[x] = catftw[x]; //gives error when catftw properly initialized cannot convert char to char*
}
cout << *lawl << endl;
for(x=lenm;x<tlen;x++)// possibly looping to much creating error
{
lawl[x] = sub[x - lenm];// when I started overwriting lawl at zero this worked with a build but at no other point
}
cout << *lawl << endl;
return tlen;
}
Thank You for your time. Please tell me anything that you think I should do differently in my code or posting.