error: cannot convert 'double*' to 'char*' for argument '1' to 'void swap(char*, char*, unsigned int)'

前端 未结 3 349
悲&欢浪女
悲&欢浪女 2021-01-29 00:14
#include 

void swap( char* pA,  char* pB, unsigned tam) {
    for( unsigned i = 0; i < tam; i++) {
        char tmp = *pA;
        *pA = *pB;
                 


        
3条回答
  •  抹茶落季
    2021-01-29 00:43

    I get the error message in the title ? Because you are passing double variable address and catching with char* so compiler is saying

    expected ‘char *’ but argument is of type ‘double *’.

    So you have two ways either typecast the address of double variable as char* or catch with double* itself.

    Case 1:

    void swap( double* pA,  double* pB, unsigned int tam) {
            double tmp = *pA;
            *pA = *pB;
            *pB = tmp;
    }
    
    int main(int argc, char** argv) {
            double a = 1.0;
            double b = 2.0;
            printf("linea: %d - antes a(%f) b(%f)\n", __LINE__, a, b);
            swap(&a, &b, sizeof(double)); //This line gives the error
            printf("linea: %d - despues a(%f) b(%f)\n", __LINE__, a, b);
            return 0;
    }
    

    Case 2 :- Second way is typecast the address of double variable as char* send it to swap()

    void swap( char *pA,  char *pB, unsigned int tam) {
            for( unsigned i = 0; i < tam; i++) {
                    char tmp = *pA;
                    *pA = *pB;
                    *pB = tmp;
                    pA = pA + 1;
                    pB = pB + 1;
            }
    }
    int main(int argc, char** argv) {
            double a = 1.0;
            double b = 2.0;
            printf("linea: %d - antes a(%f) b(%f)\n", __LINE__, a, b);
            swap((char*)&a, (char*)&b, sizeof(double)); //typecast &a to (char*)&a
            printf("linea: %d - despues a(%f) b(%f)\n", __LINE__, a, b);
            return 0;
    }
    

提交回复
热议问题