Link to home
Start Free TrialLog in
Avatar of sint4x
sint4xFlag for Canada

asked on

Adding to char Arrays via loops

What I am trying to do is generate lists of files in folders and store them in a char array. However, I dont know how to add a filename on the next loop. How do you add things to a character array?

You cant do it like this:

char ch = new char[];

ch = "hi";

ch = ch + "hi"; // does not work

ch += "hi"; // does not work


I tried using strcat() but my program crashes whenver I use it.

Anyone?data2
Avatar of Axter
Axter
Flag of United States of America image

>>char ch = new char[];

The above should be the following:

char *ch = new char[123]; //Where 123 is the size of the array that you want
char *ch = new char[123];

strcpy(ch, "Hello ");
strcat(ch, "World");

cout << ch << endl;
Avatar of sint4x

ASKER

Ahh, i see the only reason why it keeps crashing is because I didn't specify an array size.

Now how do I reset the size after I add things? (getting a directory list could be very large.)
ASKER CERTIFIED SOLUTION
Avatar of Axter
Axter
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
>>Now how do I reset the size after I add things? (getting a directory list could be very large.)

Otherwise, you would need to create an array of pointer, which would require that you have an idea of the quantity of file names you're going to store in advance.

Then you would have to assign space for each file name, and set it to an each array pointer item.
Avatar of CmdrRickHunter
CmdrRickHunter

do you understand pointers?  If not, then this is going to be some black magic:

char* data = new char[256],
      * p = data; // "p" moves along in the "data" array
const char[] filename1 = "hello\n";
const char[] filename2 = "world\n";
strcpy(p, filename1); // put "hello\n" into p (into the data array)
p += strlen(filename1); // this is the pointer magic
strcpy(p, filename2);
p += strlen(filename2);


what the "p += strlen(theStringJustCopied)" does is move p forward in memory, so that it points to the character one after the last character you added.

just remember, even though p is a char*, dont delete it!!  All its doing is pointing to memory that got allocated as part of "data".  DELETE "data" NOT "p"!!!


if you really want to:

void AddToBuffer(char*& inP, const char* inNewString)  // if this doesn't work, try char &*
{
   strcpy(inP, inNewString);
   inP += strlen(inNewString);
}


then you can do
char* data = new char[1250];
char * p = data;
AddTobuffer(p, "Hello ");
AddToBuffer(p, "world");


the trick to that working is the "pass pointer by reference", which passes a char*, but does so by reference so that we can change what the pointer is pointing AT.