简体   繁体   中英

Invalid operands to binary * (have ‘ab {aka struct a}’ and ‘ab * {aka struct a *}’)

I wrote a program to swap two structures in an array and my coding is as follows

#include <stdio.h>
struct a {
    char *name;
    int id;
    char *department;
    int num;
};
typedef struct a ab;

void swap(ab *, ab *);

int main(int argc, char *argv[])
{
    ab array[2] = {{"Saud", 137, "Electronics", 500}, {"Ebad", 111, "Telecom", 570}};
    printf("First student data:\n%s\t%d\t%s\t%d", array[0].name, array[0].id,
           array[0].department, array[0].num);

    printf("\nSecond Student Data\n%s\t%d\t%s\t%d\n", array[1].name, array[1].id,
           array[1].department, array[1].num);

    swap(&array[0], &array[1]);
    // printf("")
    return 0;
}

void swap(ab *p, ab *q){
    ab tmp;
    tmp = *p
    *p = *q;
    *q = tmp;
}

On compiling it it gives an error,

newproject.c: In function 'swap':
newproject.c:26:3: error: invalid operands to binary * (have 'ab {aka
struct a}' and 'ab * {aka struct a *}')
*p=*q;

What is the mistake?

There's a missing semicolon at the end of line 26 (the previous line).

tmp=*p

Due to this, the compiler considers the next line to be part of the same statement, meaning that the entire statement is interpreted as:

tmp=*p * p = *q;

The second * is seen as a multiply of two operands - *p and p - which is where the error message comes from:

invalid operands to binary * (have 'ab {aka struct a}' and 'ab * {aka struct a *}')

(Because *p is of type ab , and p is of type ab * ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM