2016-04-09 118 views
0

我試圖通過將它們作爲指針傳遞給初始化函數來初始化數組。我的程序編譯沒有錯誤,但是當我運行它時;它打印出字符數並停止。數組初始化函數:傳遞數組作爲指針:C++

這是我到目前爲止有:

#include<iostream> 
#include<cctype> 
#include<string> 
#include<iomanip> 

using namespace std; 

void initialize(int *array, int n, int value);  

int main() 
{ 
char ch; 
int punctuation, whitespace, digit[10], alpha[26]; 

punctuation = 0, whitespace = 0; 

initialize(digit, sizeof(digit)/sizeof(int), 0); 
initialize(alpha, sizeof(alpha)/sizeof(int), 0); 

while(cin.get(ch)) 
{ 
    if(ispunct(ch)) 
     ++punctuation; 
    else if(isspace(ch)) 
     ++whitespace; 
    else if(isdigit(ch)) 
     ++digit[ch - '0']; 
    else if(isalpha(ch)) 
    { 
     ch = toupper(ch); 
     ++alpha[ch - 'A']; 
    } 

    if(whitespace > 0) 
    { 
     cout << "Whitespace = " << whitespace << endl; 
    } 

    if(punctuation > 0) 
    { 
     cout << "Punctuation = " << punctuation << endl; 
    } 

    cout << setfill('-') << setw(17) << '-' << setfill(' ') << endl; 
    cout << " Character " << " Count " << endl; 
    cout << setfill('-') << setw(17) << '-' << setfill(' ') << endl; 


    return 0; 
} 
} 

void initialize(int *array, int n, int value) 
{ 
    int i;  

    for (i = 0; i < n; ++i) 
    { 
    value += array[i]; 
    } 
} 

我不知道我在做什麼錯在這裏。雖然,對於指針在傳遞到另一個函數後如何工作,我有點困惑。有人可以解釋嗎?

謝謝

+0

在初始化函數中,輸出n的值。 – MikeC

+0

「停止」?掛起?崩潰?剛出口? – hyde

+0

它打印字符數然後退出 – Ambrus

回答

2

你可能想
一)

void initialize(int *array, int n, int value) 
{ 
    int i;  

    for (i = 0; i < n; ++i) 
    { 
    // no: value += array[i]; but: 
    array[i] = value; 
    } 
} 

也看到std::fill

和b)移動return 0;離開while循環體

cout << " Character " << " Count " << endl; 
    cout << setfill('-') << setw(17) << '-' << setfill(' ') << endl; 
    } 
    return 0; 
} 

編輯:關於)
您可以使用

std::fill(std::begin(digit), std::end(digit), 0); 
std::fill(std::begin(alpha), std::end(alpha), 0); 

,而不是你的初始化()函數或(給定上下文)剛剛

int punctuation, whitespace, digit[10]={0}, alpha[26]={0}; 
+0

哦哇,現在我覺得真的很愚蠢,因爲我甚至沒有注意到,返回0;是在while循環裏面的,你修改我的函數的方式是我最初的方式。謝謝,VolkerK。 – Ambrus

0

如果在C++開發,爲什麼不使用向量? (使用數組*是非常C風格)。

vector<int> array(n, value); 

n =整數數量。 value =放置在每個數組單元格中的值。