Home > Back-end >  i couldn't figure it out why compiler show this "error: 'i' was not declared in
i couldn't figure it out why compiler show this "error: 'i' was not declared in

Time:01-09

I tried to print the elements of the array by using class templates but it shows error in the class constructor named array like this:

In constructor 'Array<T>::Array(T*, int)':
./6cf77951-ab9d-463e-86aa-763810936e52.cpp:20:18: error: 'i' was not declared in this scope
      cout<<*(ptr i)<<" ";

I was expecting it to print the elements of the array for every for loop iteration

#include <iostream>
using namespace std;

template <typename T> class Array {
private:
    T* ptr;
    int size;

public:
    Array(T arr[], int s);
    void print();
};

template <typename T> Array<T>::Array(T arr[], int s)
{
    ptr = new T[s];
    size = s;
    for (int i = 0; i < size; i  )
        ptr[i] = arr[i];
         cout<<*(ptr i)<<" ";
}

template <typename T> void Array<T>::print()
{
    for (int i = 0; i < size; i  )
        cout << " " << *(ptr   i);
    cout << endl;
}

int main()
{
    int arr[5] = { 1, 2, 3, 4, 5 };
    Array<int> a(arr, 5);
    a.print();
    return 0;
}

CodePudding user response:

Easy mistake to make

for (int i = 0; i < size; i  )
     ptr[i] = arr[i];
     cout<<*(ptr i)<<" ";

should be

for (int i = 0; i < size; i  )
{
     ptr[i] = arr[i];
     cout<<*(ptr i)<<" ";
}

CodePudding user response:

Your loop, where i is defined, only has the line "ptr[i] = arr[i];". The next line "cout<<*(ptr i)<<" ";" is no longer part of the loop's body and thus does know nothing about i. You need the curly braces for multiple lines.

  • Related