字符数组和指针
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
检查马洛克的退货
相关文章:
- 指向指向字符数组的指针数组的指针
- 通过指向指针数组的指针访问子类的属性
- C++,指针数组,指向双链表中的条目
- 在C++中,如何初始化指向wchar_t*的指针数组(生成wchar_t**)
- C++从函数指针数组调用函数
- 关于指向指针数组的指针
- 将返回值存储在函数指针数组的指针中是如何工作的?
- 将链表转换为指针数组时出错
- C++ 对象指针数组的复制构造函数
- C++ - 循环访问指针数组会导致错误
- 删除指针数组 (C++) 中的元素
- 如何循环访问 cpp 中的函数返回的字符指针数组
- 将函数指针数组中的函数指针作为模板参数传递
- Google Or-Tools Glop:如何创建指向 const 对象的指针数组?
- 具有推导参数的模板函数指针数组变量
- 如何模板化堆栈分配的多态指针数组到接口,包括派生类型的相应点?
- C++指针数组到字符数组中的特定位置
- 如何在C++中复制指针数组的数据
- 初始化类中的指针数组,并在另一个类中检索它
- 尽管直接设置了指针数组,但仍为空