[英]char array and pointer
#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;
}
谁能告诉我这是怎么回事? 当它进入if子句时,它没有响应。
您的“ pc”变量是由20个指向字符的指针组成的数组(本质上是由20个字符串组成的数组)。
如果必须使用指针,请尝试:
#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;
}
修改一些代码。 试试吧
#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;
}
char *pc[20];
这意味着pc
是大小为20的数组,可以容纳20个指向char
指针。 在您的程序中,您只需要在该变量pc
存储一个字符串或文本(无论如何),那么为什么要声明它保留20个字符串( 20 pointer to char
)。
现在,程序中的pc
数组也未设置为NULL
。 因此pc
指向大约20个垃圾值。 这是完全错误的。 cin
将尝试将日期从stdin
写入pc
数组的第一个索引中的某些垃圾指针。
所以cin>>*pc;
在程序中将导致崩溃或其他一些内存损坏。
以任何一种方式更改程序
第一种方式
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];
第二路
char *pc = new char[MAX_TEXT_SIZE];
cout<<"Type the text" << endl;
cin>>pc;
第三种方式
char pc[MAX_TEXT_SIZE];
cout<<"Type the text" << endl;
cin>>pc;
注意:请注意NULL
检查是否返回了malloc
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.