Hi there, i wrote a following code, declared 4 char pointers as parameters of vector, the function invector is there to initialize the null char pointers, but the program walks of after the 1st iteration of for loop in invector function,why does that happen??
#include<iostream.h>
#include<conio.h>
#include<vector.h>
using namespace std;
void invector(vector<char*> &);
void outvector(vector<char*> &);
int main()
{
vector<char*> name(4);
invector(name);
outvector(name);
return 0;
getch();
}
void invector(vector<char*> &array)
{
for(int i=0;i<array.size();i++)
{
cin>>array[i];
}
}
void outvector(vector<char*> &array)
{
for(int i=0;i<array.size();i++)
{
cout<<array[i]<<endl;
}
}
When you pass a char pointer to the the cin >> operator it assumes the pointer is pointing to an array that is large enough to hold all the characters in the next word read from cin, plus the null terminator '\0'. You pass a null pointer so when it tries to write to the array it crashes. I recommend that you use std::string instead of char pointers to handle strings because that makes it much easier. You just need to include <string> and change all occurrences of char* to string.