没有[],数组等于什么? C ++

时间:2014-04-04 04:20:10

标签: c++ arrays pointers

由于某种原因,打印出来的第一个数字不遵守main函数中的for循环,告诉它的范围是0-10;但是什么时候

void printArray(int augArray[5])
{
    cout << *augArray;         //this line is taken out, the for loop proceeds with normal 
    for (int i = 0; i < 5;)       //outputs, when the first line is kept also the for loop only
    {                                //produces 4 other numbers, just curious to why this is 
        cout << augArray[i] << endl;     //happening, thanks.
        i++;
    }
}

int main()
{
    srand(time(0));
    int anArray[5];

    for(int j = 0; j < 5;)
    {
        anArray[j] = rand() % 11;
        j++;
    }

    printArray(anArray);
    cout << anArray;
}

2 个答案:

答案 0 :(得分:3)

在不带方括号的表达式中使用数组名称时,其值等于指向数组初始元素的指针,即表达式中的augArray与{{1}相同}。因此,&augArray[0]*augArray相同,只是*(&augArray[0])(星号和&符号相互抵消)。

输出看起来很奇怪的原因是您在打印augArray[0]后没有放置行尾字符。您在输出中看到的“奇怪数字”实际上是重复两次的数组的初始元素。

答案 1 :(得分:0)

除了第一个输出与以下输出混合外,它应该可以正常工作。要更清楚地看到它,您应该在打印出第一个元素后添加换行符:

更改

cout << *augArray; // print the first element

cout << *augArray << endl; // print the first element and go to a new-line

直播:http://ideone.com/y16NeP


旁注:您可以简单地将i++/j++添加到for行,例如for (int i = 0; i < 5; i++)