I want the body back from the function, but I'm making a mistake. C++



  • I wanted to do a function that would create a mass and return it to the main, but something went wrong. Explain where I did wrong.

    #include <iostream>
    using namespace std;
    

    int create_board () {
    int board[10];
    for (int i = 0;i<10;i++) {
    board[i] = i;
    }
    return board;
    }

    int main () {
    int board = create_board();
    for (int i = 0;i<10;i++) {
    cout >> board[i] << " ";
    }
    }



  • First,in functions create_board variable board You have a type. const int * (i.e. mass int) And you're trying to make this variable-type meaning. int here:

    int board = create_board();
    

    I think it makes a mistake to make a difference. Should be replaced by:

    int* board = create_board(); // Звёздочка после int 
    

    and the designation of the function, respectively,

    int* create_board ()
    

    SecondWhen you do this:

    int board[10];
    

    memory underground is emitted in the glass ( https://ravesli.com/urok-105-stek-i-kucha/ ) And all memory in the glass shall be cleaned when the relevant variable comes out. https://ravesli.com/urok-48-lokalnye-peremennye-oblast-vidimosti-i-vremya-zhizni/ ♪ In summary, as soon as your code reaches the figure boxes that complete the function create_boardthe memory of the mass board it is cleared and, therefore, all values in it become inaccessible. There's a mistake.

    Now what to do with it. If it's so bad with the glass, you're gonna have to remembrance it in a pile of dynamism, replacing it with:

    int board[10];
    

    Here's this:

    int* board = new int[10];
    

    Attention, don't forget to clear your memory when you don't need it, so:

    int* board = create_board(); // Создаёте массив
    //... Используйте массив, как хотите
    delete[] board; // Когда стал не нужен, чистите память
    

    ThirdWell, at the end of the day, where does the sign of the space in the flow be placed? cout? This one. <<! You have one, then another. ♪ ♪

    P.S. In the notebook, you write your code... IDE, the majority of these mistakes should have told you.


Log in to reply
 


Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2