initializing an array

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
I want to create a function called reset which will initialize array myIntArray so that the value of each location will be the value of its index.  For example, after function reset has been called, position myIntArray[0] will be set to the value 0 since its index is 0.  Similarly, myIntArray[1] and myIntArray[2] will be set to 1 and 2 respectively and so forth.
this is what i have been trying but when i call the function nothing happens .i also canot use pointers in this function cause we are not on that topic yet .


void MyList::reset(){
for(int i = 0;i<ARRAY_SIZE;i++){

    myIntArray[i]=i;

}
this is me calling the function 
#include  "mylist.h"
#include <iostream>
using std::cout;
using std::cin;
using std::endl;

int main(void)
{  
    MyList list;

   
   
    list.reset();
    list.printArray(ARRAY1, 20,true);

}

and this is the .h
#include "mylist.h"

#include<iostream>
using namespace std;


void MyList::reset(){
for(int i = 0;i<ARRAY_SIZE;i++){

    myIntArray[i]=i;

}


Last edited on
http://www.cplusplus.com/articles/jEywvCM9/
Please edit so we can read it.
And actually include the .h file containing your class declaration.
A simple example without the added expense of being in a class. The main point is using a C++ algorithm to do the actual work, std::iota:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>
#include <numeric>  // for std::iota

void display(int [], int);
void reset(int*, int);

int main()
{
   const int num_elems { 10 };

   // initialize all elements to zero
   int arr[num_elems] { };

   display(arr, num_elems);

   reset(arr, num_elems);

   display(arr, num_elems);
}

void display(int arr[], int num_elems)
{
   for (auto itr { arr }; itr != arr + num_elems; itr++)
   {
      std::cout << *itr << ' ';
   }
   std::cout << '\n';
}

void reset(int* arr, int num_elems)
{
   // https://en.cppreference.com/w/cpp/algorithm/iota
   std::iota(arr, arr + num_elems, 0);
}

Personally I'd prefer to work with C++ containers instead of old school C arrays. Passing a std::vector, for instance, doesn't need all the fancy "foot-work" a C array does. C++ containers don't devolve to a pointer to an array.

And PLEASE, learn to use code tags, they make reading and commenting on source MUCH easier.
http://www.cplusplus.com/articles/jEywvCM9/

Hint: you can edit your post and add code tags.
Topic archived. No new replies allowed.