Returning a char* array?

I am new here.
I was creating a program, and I needed to return a char* array from this:
http://www.codeproject.com/KB/cpp/IniReader.aspx
I am using the
1
2
3
4
5
6
7
char* CIniReader::ReadString(char* szSection, char* szKey, const char* szDefaultValue)
{
 char* szResult = new char[255];
 memset(szResult, 0x00, 255);
 GetPrivateProfileString(szSection,  szKey, szDefaultValue, szResult, 255, m_szFileName); 
 return szResult;
}

function. I have this code:
1
2
3
    char str;//[256];
    str=*ini.ReadString("Section", "strVal", "???");
    cout<<str<<endl;


and it should output "Pineapple".
(ini file is here)
1
2
3
[section]
strVal=Pineapple
intVal=1234


But, it outputs "P". I know this is because I turned a entire array into just one char.


How do I store the entire array in "str".
char is a single character
char* is a pointer to one or more characters (usually more -- ie: a string)

1
2
char str;//[256];
str=*ini.ReadString("Section", "strVal", "???");


ReadString returns a pointer, which you then are deferencing with *, which only gets you the first character in the string.

To get the whole string, you can just take the pointer:

1
2
char* str;
str = ini.ReadString(...)


but also note that because this string is allocated with new[], it must be deleted with delete[] or else you get memory leaks!

1
2
3
char* str = ini.ReadString(...);
// do whatever with 'str' here
delete[] str;


This is fugly and easy to forget to do, which is why you generally do not return pointers from functions like this. Instead the more common way is to provide a pointer to the buffer as a function argument:

1
2
3
4
5
6
7
8
9
10
11
void CIniReader::ReadString(char* szResult,char* szSection,char* szKey,const char* szDefaultValue)
{
  szResult[0] = 0;
  GetPrivateProfileString( ... );
}


// elsewhere:

char str[255];
ini.ReadString(str,"Section","strVal","?");


As a side note, you might run into problems with "???" as multiple consecutive ? symbols have a very obscure special meaning in C++.
Oh Thanks. I started C++ programming a while ago, and I just started to get back to it. I forgot the advanced basics.
Topic archived. No new replies allowed.