-
deleting pointers....
I have a problem with a program i just wrote, i haven't used pointers fo a while so it is prolly something stupid.
Code:
#include <iostream>
using namespace std;
int main()
{
char buffer[100] = "\0";
char *Names[10];
char *kill = new char;
int size = 0;
for(int i = 0; i < 10; i++)
{
cout << "Please enter your name: ";
cin.getline(buffer, 100);
size = strlen(buffer);
Names[i] = new char[size];
strcpy(Names[i], buffer);
}
for(i = 0; i < 10; i++)
{
for(int j = 0; j < strlen(Names[i]); j++)
{
cout << Names[i][j];
}
cout << endl;
}
for(i = 9; i > -1; i--)
delete [] Names[i];
return 0;
}
i tried:
Code:
for(i = 0; i < 10; i++)
delete [] Names[i];
-and-
char * kill;
for(i = 0; i < 10; i++)
{
kill = Names[i];
delete [] kill;
}
-
What is the problem? You never check if an allocation fails, so trying to do something with that memory is bad. Also, you allocate memory for kill, but you never use it nor deallocate its memory.
Finally, why are you looping backwards when deallocating Names? No need for that (If you had allocated memory for an array of pointers that you allocate memory for, you have to be careful how you deallocate it but in this case when all are on the same level you don't need to).
And this:
I'm not sure, but I think you need to do this:
Since you want an array of pointers and not a pointer to an array, which would be this:
-
What is the problem?
So, first of all - this kill. U never use it.
Also, include string.h (I have used bc++ 3.1)
and at the end, I had no problems using your program. It asked me 10 times for my name, and then it outputted them. There was no problem.
-
You can use _set_new_handler() to handle allocation failure.
Code:
#include <iostream>
using namespace std;
int Error_Handler()
{
cerr << "Memory Allocation failed.........";
}
int main()
{
_set_new_handler(Error_Handler);
char *p = new char[1000000];
cout << "Memory Allocation OK" << endl;
delete p;
return 0;
}
-
thanks for your reply's i will check your suggestions 2moro, as i do not have a compiler at home. and sikamikaniko i am using MSVC++ 6.0 so perhaps VC is just a bit more picky =]
-
You need to allocate size+1 to hold the terminator. cout overloads << for char * to do the correct thing, just
cout << names[i];
will work fine.
You have imported all of namespace std, why not use some of it?
Code:
#include<iostream>
#include<vector>
#include<string>
using std::cout;
using std::cin;
using std::endl;
int main() {
std::vector< std::string > names;
std::string str;
cout << "Please enter names, or a blank line to quit." << endl;
cout << ":";
std::getline(cin,str);
while(str != "") {
names.push_back(str);
cout << ":";
std::getline(cin,str);
}
for(int i=0;i<names.size();i++) {
cout << names[i] << endl;
}
return 0;
}
Look how many problems go away!