2016-04-09 117 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 =放置在每个数组单元格中的值。