2012-05-31 111 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的返回