2012-05-31 112 views
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子句时它没有响应。字符数组和指针

+1

你确定你想要一个指向字符的指针数组吗?它看起来像你只是像字符数组一样使用它。 – chris

+0

我想你只需要一个字符数组:char * char [20],而不是char * pc [20] –

+0

是的,你是对的,这是我的一个错误。我想让我的数组[20]函数。然后在函数syn中,我想对数组进行搜索。现在我改变了syn: int syn(char * pc,char ch,int n)但是它在if循环中有错误。 一元类型参数无效* –

回答

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; 
} 
+0

nope.i想用指针 –

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; 
} 
+0

您忘记了'delete [] pc'。 –

+0

我做到了。在我的防守中,我不会用char * –

+0

这样做我错过了什么?你声明'char * pc = new char [20];'但是你不会释放它(你让操作系统去做)。 –

0

char *pc[20];这意味着pc是大小20,能容纳20个指向char的阵列。在你的程序中,你只需要在变量pc中只存储一个字符串或文本(不管),所以为什么它声明要存放20个字符串(20 pointer to char)。

现在pc在你的程序中数组并不是NULL也设定的。所以pc指向了大约20个垃圾值。它完全错误。 cin会尝试将stdin中的日期写入pc数组的第一个索引中的某个垃圾指针。

因此你的程序中的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]; 

第二方式

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