Reputation: 79
I want to declare an array of class objects for my utility. I tried declaring as below but am getting an exception. Not able to understand what am I doing wrong. here is the code section.
#include<iostream>
#include<conio.h>
using namespace std;
struct charFreqPair{
public: charFreqPair();
charFreqPair(char,int);
~charFreqPair(){}
char ch;
int freq;
};
charFreqPair::charFreqPair(){
}
charFreqPair::charFreqPair(char c , int f){
ch = c;
freq = f;
}
int main(int argc , char **argv){
char *string;
cout<<"Enter String"<<endl;
cin>>string;
charFreqPair array[128] ;
getch();
}
If I run the above code by commenting : charFreqPair array[128] ; everything works fine. But if I run the above code as it is , it's throwing following exception:
First-chance exception at 0x00d31556 in String1.exe: 0xC0000005: Access violation writing location 0x00d320fd.
I am not able to understand what am I doing wrong in declaring array of class object.
Upvotes: 0
Views: 84
Reputation: 133577
The error is not caused by the array but by the fact that you are using cin
to save the input into a uninitialized pointer:
char *string;
cin>>string;
char *string
is not initialized so dereferencing it causes the exception. Use a std::string
as you should:
std::string;
cin >> string;
Upvotes: 2
Reputation: 8614
You can not just write to a pointer that is not pointing anywhere. No wonder you are getting exceptions, you are writing on random memory.
Allocate your string
before using it.
Upvotes: 1