将数组传递给c ++代码错误中的函数

时间:2017-07-11 23:30:47

标签: c++

我正在学习C ++,我无法弄清楚为什么这段代码输出正确数量的输出(4),但只输出数字54.有人可以帮助解决它并解释我做错了吗?

onClick

4 个答案:

答案 0 :(得分:5)

您将数组限制与索引器混淆。应该是:

 cout << arr[c] << endl;

数组是零索引的。您正在尝试打印出超出边界的元素,从而调用未定义的行为。根据平台,您的输出可能看起来像四个0或类似-858993460的内容。按照惯例,计数器变量通常以字母i开头。

答案 1 :(得分:3)

由于<?php declare(strict_types = 1); require_once ('hhb_.inc.php'); const USERNAME = '???'; const PASSWORD = '???'; $hc = new hhb_curl ( 'https://www.maxityre.fr/', true ); $html = $hc->exec ()->getResponseBody (); $csrf_token = (new DOMXPath ( @DOMDocument::loadHTML ( $html ) ))->query ( '//input[@name=\'callback\']' )->item ( 0 )->getAttribute ( "value" ); $html = $hc->setopt_array ( array ( CURLOPT_POST => true, CURLOPT_URL => 'https://www.maxityre.fr/', CURLOPT_POSTFIELDS => http_build_query ( array ( 'action' => 'login', 'callback' => $csrf_token, 'login' => USERNAME, 'password' => PASSWORD ) ) ) )->exec ()->getResponseBody (); if (false !== stripos ( $html, 'Erreur d\'identification' )) { throw new Exception ( 'failed to login! (maybe wrong username/password?)' ); } echo "logged in!"; 为4,cout << arr[x] << endl; cout << arr[c] << endl; 。但是x只有四个条目,它没有第五个条目。所以你输出垃圾。你可能在循环中意味着arr[x]

答案 2 :(得分:2)

更改

your password here

application/x-www-form-urlencoded

答案 3 :(得分:1)

函数

中的循环中存在拼写错误
for(int c = 0;c < x;c++){
    cout << arr[x] << endl;
               ^^^
}

应该有

for(int c = 0;c < x;c++){
    cout << arr[c] << endl;
               ^^^
}

变量c用作数组中的索引。

然而,该计划有几个缺点。

您不应使用以下划线开头的标识符。这些名称可以由编译器实现保留。

不要使用“魔术数字”。它们通常是造成错误的原因。

要存储对象或数组的大小,请使用size_t类型而不是类型int

该函数不会更改数组。因此,应使用限定符const声明相应的参数。

程序可以按以下方式查看

#include <iostream>

void pi( const int arr[], size_t n )
{
    for ( size_t i = 0; i < n; i++ )
    {
        std::cout << arr[i] << std::endl;
    }
}

int main()
{
    int arr[] = { 3543, 146, 961262,-242 };
    pi( arr, sizeof( arr ) / sizeof( *arr ) );
}

考虑到您可以使用标准算法输出数组,例如std::for_eachstd::copy

这是一个演示程序,它使用标准算法std::copy输出数组。

#include <iostream>
#include <algorithm>
#include <iterator>

int main()
{
    int arr[] = { 3543, 146, 961262,-242 };
    std::copy( std::begin( arr ), 
               std::end( arr ), 
               std::ostream_iterator<int>( std::cout, "\n" ) );
}