• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

C++ Help: char arrays are evil

Rapier21

Member
I want to write a pair of functions, one that converts a character array into a string and one that converts a string into a char array. I have tried and failed miserably. Here's one attempt at converting a string to a char array:

#include <iostream>
#include <string>
using namespace std;

char * String ToChar(string String);

int main()
{
string test = "hello world";
char array[] = StringToChar(test);
cout<<"test = "<<test<<" array = "<<array<<endl; // hopefully, test and array will match
return 0;
}

char * StringToChar(string String)
{
// pre: String is a nonempty, initialized string
// post: foo is a character array identical to String in content and length
const int size = String.size();
char foo[size];
for (int i = 0; i < size; i++)
foo{i}<I> = String{i} <I>;
char* fooPtr = foo;
return fooPtr;
}

Needless to say, this above code won't even compile. There are several issues that I see:
1) how to dynamically size the array foo (impossible?)
2) how to actually return the array to main (use pointers as shown?)
3) how to assign the returned value to array in main

Could someone please advise / write me something that works?

~Rapier21
</I></I>
 
There were several issues with your code. Here's some code to do what you're looking for. Look at it, and ask questions about what you don't understand 🙂

#include   <iostream.h>
#include   <string>
using   namespace   std;

char         *StringToChar(string   str);

void   main()
{
        string     str                   =   "hello   world";
        char         *pArray           =   StringToChar(str);

        cout   <<   "str         =   "   <<   str             <<   endl;
        cout   <<   "pArray   =   "   <<   pArray       <<   endl;
delete pArray;
}


char   *StringToChar(string   str)
{
        char         *pArray   =   new   char[str.size()+1];

        for(int   ctr=0;ctr   <   str.size();   ctr++)
        {
                pArray[ctr]       =   str[ctr];
        }

        pArray[ctr]               =   0;
        return   pArray;
}

 
Thank you, sir, that was quite helpful. I forgot all about the "new" command...very useful.

Oh, and for anyone that cares, I was being dumb and made conversion from char[] to string overly complicated...its just:
char array[] = "hello";
string Str = array;

~Rapier21
 
Back
Top