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

What does an array equal to without the [ ]? c++

本文关键字:什么 C++ 于什么 数组 没有      更新时间:2023-10-16

由于某种原因,打印出的第一个数字不遵守主函数中的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;
}

当数组名称用于后面没有方括号的表达式时,其值等于指向数组初始元素的指针,即 表达式中的augArray&augArray[0]相同。因此,*augArray*(&augArray[0]) 相同,只是augArray[0](星号和与号相互抵消)。

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

它应该工作得很好,除了第一个输出与以下输出混合。为了更清楚地看到它,您应该在打印出第一个元素后放置一个换行符:

改变

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++)