Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何反转字符数组中的元素?C++;_C++_Arrays - Fatal编程技术网

C++ 如何反转字符数组中的元素?C++;

C++ 如何反转字符数组中的元素?C++;,c++,arrays,C++,Arrays,我是编程新手,我正在尝试反转字符数组的内容。但我似乎得到了输出中第一个元素的垃圾值。有人能告诉我我做错了什么吗 int main() { int size = 0; char arr[100]; cout << "Enter how many elements are added to array" << endl; cin >> size; cout << "Enter &q

我是编程新手,我正在尝试反转字符数组的内容。但我似乎得到了输出中第一个元素的垃圾值。有人能告诉我我做错了什么吗

int main() {
    int size = 0;
    char arr[100];

    cout << "Enter how many elements are added to array" << endl;
    cin >> size;
    cout << "Enter " << size << " elements " << endl;

    for(int i = 0; i < size; i++)
    {
        cin >> arr[i];
    }

    cout << "Input: [ " ;
    for (int i = 0; i < size; ++i) {
        cout << arr[i] << "  ";
    }
    cout << "]" << endl;

    cout << "Output: [";
    for(int j = size; j >= 0; j--)
    {
        cout << arr[j] << " ";
    }
    cout << "]" << endl;
}
intmain(){
int size=0;
char-arr[100];
cout大小;

cout问题是您正在打印一个从未初始化过的元素:

for(int j = size; j >= 0; j--)
{
    cout << arr[j] << " ";
}
for(int j=size;j>=0;j--)
{

cout
for(int j=size;j>=0;j--)
正在
size+1
元素上循环。由于未定义的行为,第一个值输出(
arr[size]
)是垃圾,因为您从未将其初始化为任何内容。您打印的第一个元素是
arr[size]
这是在使用的元素结束之后。我得到了它。我的错,一个新手的错误。谢谢你的帮助!问题为什么结束了?没有“输入错误”这里。这是一个非常有效的问题。事实上,这是调试器所犯的错误。当查看数组时,您会发现奇怪的值正好位于索引“size”上的最后一个条目之后。
for (int j = size - 1; j >= 0; j--)
{
    cout << arr[j] << " ";
}