char数组和指针

时间:2012-05-31 14:03:51

标签: c++ arrays pointers

#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子句时它没有响应。

3 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分: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;
}

答案 2 :(得分:0)

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的返回

相关问题