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

橙三吉。 提交于 2019-12-23 19:07:27

问题


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?


回答1:


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 *).



来源:https://stackoverflow.com/questions/40134786/invalid-operands-to-binary-have-ab-aka-struct-a-and-ab-aka-struct-a

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!