Zeshan Sajid February 2016

Error: cannot convert int ** to int * (templates, dynamic allocation arrays)

I have written 3 template functions but when I run the code, it gives error on the first function's body where the memory to arr is dynamically allocated. Following is the code, please help me in finding what I missed. Thanks

Error: Error 1 error C2440: '=' : cannot convert from 'int **' to 'int *'

#include<iostream>
using namespace std;

template<typename T>
void input(T arr, int size){
    arr = new T[size];

    for(int i=0; i<size; i++){
        cout<<"\nEnter: ";
        cin>>arr[i];    
    }
}


template<typename T>
void sort(T arr, int size){
    int temp;

    for(int j=0; j<size-1; j++){
        for(int i=0; i<size-1; i++){
            if(arr[i]>arr[i+1]){
                    temp=arr[i];
                    arr[i]=arr[i+1];
                    arr[i+1]=temp;
            }
        }
    }
}


template<typename T>
void display(T arr, int size){

    cout<<"\nAfter Sorting: "<<endl;

    for(int i=0; i<size; i++){
        cout<<arr[i]<<"\t";
    }
}

int main(){
    int* x=NULL;
    int size;

    cout<<"Enter the number of elements: ";
    cin>>size;

    cout<<"\nEnter integer values:";
    input<int*>(x, size);
//  sort(x, size);
    display<int*>(x, size);

    /***
    cout<<"\nEnter floating values:";
    input(x, size);
    sort(x, size);
    display(x, size);

    cout<<"\nEnter character values:";
    input(x, size);
    sort(x, size);
    display(x, size);
    */

    system("pause");
}

Answers


Martín Muñoz del R&# February 2016

You have a bug here:

arr = new T[size];

With your parameters, it means something like:

int *arr = new int*[size];

The type of new int*[size] is not int*

You can do something like:

template<typename T>
void input(T * &arr, int size){//
    arr = new T[size];

    for(int i=0; i<size; i++){
        cout<<"\nEnter: ";
        cin>>arr[i];    
    }
}

And in main:

    input<int>(x, size); //
//  sort(x, size);
    display<int>(x, size);

And in display:

template<typename T>
void display(T *arr, int size){

    cout<<"\nAfter Sorting: "<<endl;

    for(int i=0; i<size; i++){
        cout<<arr[i]<<"\t";
    }
}

Post Status

Asked in February 2016
Viewed 1,858 times
Voted 6
Answered 1 times

Search




Leave an answer