M
M
Muriam2019-03-19 15:46:07
C++ / C#
Muriam, 2019-03-19 15:46:07

How to add two more elements to four array elements?

in the commented line....

//добавить два элемента к массиву и посчитать кол-во элементов
#include <iostream>
#include <conio.h>

using namespace std;

int main() 
{   
    int rez;
  int arr[] = {1,8,3,2};	
    
    //arr[] += {7,8};               ????
    rez = sizeof(arr) / 4;          //кол-во элементов в массиве
    cout << rez << endl;            
    
    for (int i=0; i<=rez; i++)
        cout << arr[i] << ' ';
  
    getch();
    return 0;
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
SerJook, 2019-03-19
@Muriam

Use std::vector.

#include <iostream>
#include <conio.h>
#include <vector>
using namespace std;

int main()
{
    int rez;
    int arr_src[] = {1,8,3,2};
    std::vector<int> arr(arr_src, arr_src + sizeof(arr_src)/sizeof(arr_src[0]));

    arr.push_back(7);
    arr.push_back(8);

    rez = arr.size();          //кол-во элементов в массиве
    cout << rez << endl;

    for (int i = 0; i < rez; i++)
        cout << arr[i] << ' ';

    getch();
    return 0;
}

You also have an error in the exit condition of the loop.

M
Mercury13, 2019-03-19
@Mercury13

You need either an array with a margin (for example, for 6 places), or a dynamic one (for example, std::vector).
C++ is a rather low-level language, and the programmer himself can see where memory is dynamically allocated and where it is allocated in advance.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question