LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   About allocated memory in C++ (https://www.linuxquestions.org/questions/programming-9/about-allocated-memory-in-c-270968/)

Ephracis 12-27-2004 08:39 PM

About allocated memory in C++
 
I use a lot of strings and need to make my code efficient with memory.

The first thing is how is the best way to use strings when you don't now the size of it or when you need to use pointer so you can use as return value?

The second thing. Lets say I have a function that allocates memory, fills it with a string and returns a pointer to that memory.

The calling function uses this function as argument in something like strcmp()? How can I now free that memory after I am done?

leonscape 12-27-2004 09:12 PM

What you describing is C strings. If your going to be using unknow size strings all over your code in C++ I suggest you use the string class thats in the STL.

Belows an example.

Code:

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

int main()
{
  string str1, str2, str3, str4;
  str1 = "The First String";
  str2 = "The Second String";

  str3 = str1 + " " + str2;
  cout << "String 3:" << str3 << endl;;

  str4 = str1;
  cout << "String 4:" << str1 << endl;

  if( str1 == str4 )
      cout << "String 1 is equal to string 4" << endl;
  else
      cout << "String 1 is not equal to string 4" << endl;

  str3 = str2;
  if( str1 == str3 )
      cout << "String 1 is equal to string 3" << endl;
  else
    cout << "String 1 is not equal to string 3" << endl;
};


suowei1979 12-28-2004 02:56 AM

thx£º£©


All times are GMT -5. The time now is 06:31 PM.