Reputation: 83
#include <iostream>
using namespace std;
int syn(char *pc[], char, int);
int main ()
{
char *pc[20];
char ch;
cout<<"Type the text" << endl;
cin>>*pc;
cout<<"Type The character:" << endl;
cin>>ch;
int apotelesma = syn(&pc[0], ch, 20);
cout<< "There are " << apotelesma << " " << ch << endl;
system("pause");
return 0;
}
int syn(char *pc[],char ch, int n){
int i;
int metroitis=0;
for (i=0; i<n; i++){
if (*pc[i]==ch){
metroitis++;
}
}
return metroitis;
}
Can anybody tell me what is wrong with that? Its not responding when it gets inside the if clause.
Upvotes: 0
Views: 522
Reputation: 13484
char *pc[20];
This means pc
is array of size 20, which can hold 20 pointers to char
. In your program you need to store only one string or text (whatever) in that variable pc
, so why its declared to hold 20 strings(20 pointer to char
).
Now pc
array in your program is not NULL
setted also. So pc
is pointing to some 20 garbage values. Its totally wrong. cin
will tries to write the date from stdin
to some junk pointer in the first index of the pc
array.
So cin>>*pc;
in your program will leads to crash or some other memory corruption.
Change your program in any one of the way
1st way
char *pc[20] = {0};
for (i = 0; i < 20; i++)
{
pc[i] = new char[MAX_TEXT_SIZE];
}
cout<<"Type the text" << endl;
cin>>pc[0];
2nd way
char *pc = new char[MAX_TEXT_SIZE];
cout<<"Type the text" << endl;
cin>>pc;
3rd way
char pc[MAX_TEXT_SIZE];
cout<<"Type the text" << endl;
cin>>pc;
NOTE : Take care of NULL
check for return of malloc
Upvotes: 0
Reputation: 11
Your "pc" variable is an array of 20 pointers to characters (essentially an array of 20 strings).
If you must use pointers, try:
#include <iostream>
using namespace std;
int syn(char *pc, char, int);
int main ()
{
char *pc = new char[20];
char ch;
cout<<"Type the text" << endl;
cin>>pc;
cout<<"Type The character:" << endl;
cin>>ch;
int apotelesma = syn(pc, ch, strlen(pc));
cout<< "There are " << apotelesma << " " << ch << endl;
system("pause");
return 0;
}
int syn(char *pc,char ch, int n){
int i;
int metroitis=0;
for (i=0; i<n; i++){
if (pc[i]==ch){
metroitis++;
}
}
return metroitis;
}
Upvotes: 1
Reputation: 3678
modify some codes. try it
#include <iostream>
using namespace std;
int syn(char pc[], char, int);
int main ()
{
char pc[20];
char ch;
cout<<"Type the text" << endl;
cin>>pc;
cout<<"Type The character:" << endl;
cin>>ch;
int apotelesma = syn(pc, ch, 20);
cout<< "There are " << apotelesma << " " << ch << endl;
system("pause");
return 0;
}
int syn(char pc[],char ch, int n){
int i;
int metroitis=0;
for (i=0; i<n; i++){
if (pc[i]==ch){
metroitis++;
}
}
return metroitis;
}
Upvotes: 0