字符数组和指针

char array and pointer

本文关键字:指针 数组 字符      更新时间:2023-10-16
#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检查马洛克的退货