can you tell me why this error appears? it concerns function pointers

52 views Asked by At

main.cpp

#include <iostream>
#include "prototipo.hpp"

using namespace std;

int main(){

int num_elem;
int minimo;

void (*compare)(int* x, int* y);
compare comp;
comp = swap;

cout << "Inserire numero di elementi: ";
cin >> num_elem;

int *pointA = new int[num_elem];

ordinamentoArray (pointA, num_elem, comp);

}

prototipo.hpp

#ifndef PROTOTIPO_HPP
#define PROTOTIPO_HPP

void ordinamentoArray (int pointA[], int num_elem, compare comp);
void swap(int* x,int* y);

#endif

corpo.cpp

#include <iostream>
#include "prototipo.hpp"

using namespace std;

void swap(int* x, int* y){

  int temp = *x;
  *x = *y;
  *y = temp;
}

void ordinamentoArray (int pointA[], int num_elem, compare comp){

  int indice;
  int indice2;
  int temp;

  for(indice=0; indice<num_elem; indice++){
    for(indice2=indice; indice2>0 && pointA[indice2]<pointA[indice2-1]; indice2--){

      if(pointA[indice2] < pointA[indice2-1]){
        comp(&pointA[indice2], &pointA[indice2-1]);
      }
    }
  }
}

These are the errors that appear. Among them, the main one is "error: 'compare' has not been declared". I honestly don't know what the mistake is. Can anyone give me a useful tip for solving the problem? I don't know maybe I made a mistake in declaring the function pointer, or I made a mistake passing the parameter

2

There are 2 answers

1
Vlad from Moscow On BEST ANSWER

In this function declaration

void ordinamentoArray (int pointA[], int num_elem, compare comp);

there is used the name compare that was not yet declared.

In the function main there is defined pointer (object of a pointer type) compare to the function type void( int *, int * )

void (*compare)(int* x, int* y);

And then this object that is not a type specifier is used in this statement

compare comp;

that does not make sense.

You should include the definition of the type specifier compare in the header prototipo.hpp before the function declaration either like

typedef void ( *compare )(int *, int *);

or like

using compare = void ( * )( int *, int * );

After in main remove this declaration

void (*compare)(int* x, int* y);

Also the allocated array pointed to by the pointer pointA

int *pointA = new int[num_elem];

is passed to the function uninitialized

ordinamentoArray (pointA, num_elem, comp);

Pay attention to that it looks strange that the function that compares something returns nothing. Usually such a function in C++ returns an object implicitly convertible to the type bool.

0
srilakshmikanthanp On

error: 'compare' has not been declared

void (*compare)(int* x, int* y);
compare =swap;

or

typedef void (*compare)(int* x, int* y);
compare comp;
comp = swap;