0
#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 句に入ると応答しません。

4

3 に答える 3

1

「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;
}
于 2012-05-31T14:37:18.353 に答える
0

一部のコードを変更します。それを試してみてください

#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;
}
于 2012-05-31T14:09:35.403 に答える
0

char *pc[20];これはpc、 への 20 個のポインタを保持できるサイズ 20 の配列であることを意味しcharます。プログラムでは、その variable に 1 つの文字列またはテキスト (何でも) を格納する必要があるpcため、20 個の文字列を保持するように宣言されているのはなぜですか( 20 pointer to char)。

プログラムpcの配列NULLも設定されていません。そのpcため、約 20 のガベージ値を指しています。それは完全に間違っています。は、配列の最初のインデックスにあるジャンク ポインターにcin日付を書き込もうとします。stdinpc

そのcin>>*pc;ため、プログラムでクラッシュやその他のメモリ破損が発生します。

いずれかの方法でプログラムを変更します

第1の方法

 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];

2番目の方法

 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;

注:NULLmallocの戻りのチェックに注意してください

于 2012-06-22T05:18:28.443 に答える