3

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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Saud Farooqui
  • 27
  • 1
  • 10
  • 2
    Sometimes errors are not on the line that gets reported, but on one of the previous lines. Take a look at the previous line and see if that looks okay. Like for example maybe not missing a semicolon? – Some programmer dude Oct 19 '16 at 14:52
  • Possible duplicate of [Why doesn't compiler report missing semicolon?](http://stackoverflow.com/questions/40135392/why-doesnt-compiler-report-missing-semicolon) – Ben Aaronson Oct 20 '16 at 12:55

1 Answers1

9

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

davmac
  • 20,150
  • 1
  • 40
  • 68