Can someone who me an example on how to allocate memory in C++? I know I should be using new instead of malloc because i'm coding in C++ but I haven't found any simple examples anywhere..

Why i'm asking is because I need to create a function that searches through a string and removes a word that matches one if it finds it in the string.. I know in C I would do something like this..

int rem_word_func(char *data) {
int SzLen = strlen(data);
char buffer;
buffer=(char *)malloc(SzLen+1);
int count;
for(count=0;count<=SzLen;count++) {
if (buffer[count] == 32) ...
}
.....
return 0;
}

The reason why I need to allocate memory like that is because the size of the data in (char *data) .. can be any size, and I need to be able to copy it to another char and search through it using a loop..

Recommended Answers

All 7 Replies

Member Avatar for iamthwee

Or you could just learn how to use

string from the STL :rolleyes:

Perhaps something like this?

#include <iostream>
#include <cstring>

char *foo(char *original)
{
   size_t len = strlen(original) + 1;
   char *copy = new char[len];
   for ( size_t i = 0; i < len; ++i )
   {
      copy[i] = original[i];
   }
   return copy;
}

int main(void)
{
   char *text = foo("hello world");
   std::cout << text << '\n';
   delete[] text;
   return 0;
}

iamthwee, I would learn how to use STL but to be honest I wouldn't know where to start and from what i've searched on google I haven't found any complete tutorials that cover it extensively.

Dave, thanks for the reply.. that was exactly what I was looking for :), also.. I should use the delete operator everytime i use the new operator to deallocate memory or does it matter? In your foo function there's

char *copy = new char[len];

but no delete anywhere after, just making sure.

The pointer is returned and the memory is deleted in main.

Member Avatar for iamthwee

STL is as simple as pie :eek:

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


int main(void)
{

string wut="kido It is better to use C++ style strings kido";
int i = 0;


for(i = wut.find("kido", 0); i != string::npos; i = wut.find("kido", i))
{
    wut.erase(i, 4); // erases kido
    i++;  
}

cout<<wut; //ammended string
cout<<"\n";
system("pause");

}

Or you could just learn how to use

string from the STL :rolleyes:

string class is not a part of STL...It is part of ANSI standard C++

Member Avatar for iamthwee

string class is not a part of STL...It is part of ANSI standard C++

Ya thats wat I meant. But the way the string class behaves it more or less could be part of the STL.

Anyway, learn about c++ style strings or get left behind.
:rolleyes:

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.