Search code examples
cansi-c

incompatible types when returning type


I have a problem on convertToPoint functions.

int convertToPoint(int argc, char *argv[]) {
  struct point p;
  int x, y;

  p.x = atoi(argv[1]);
  p.y = atoi(argv[2]);

  return p;
}

Expect to return a struct of type point, but receive the follow error:

error: incompatible types when returning type ‘struct point’ but ‘int’ was expected return p;

What's the problem?


Solution

  • It's a pretty simple problem. You say you want to return a struct point but your code says that the function shall return int.

    int convertToPoint(
    ^^^
    ups, shall return int
    

    So simply change it to struct point - like:

    #include <stdio.h>
    
    struct point 
    {
        int x;
        int y;
    };
    
    struct point convertToPoint(int argc, char *argv[]) {
        struct point p;
        p.x = atoi(argv[1]);
        p.y = atoi(argv[2]);
        return p;
    }
    
    
    int main(int argc, char *argv[]) {
        struct point p = convertToPoint(argc, argv);
        printf("%d %d\n", p.x, p.y);
    }
    

    That said - it's a bit strange to pass argc when it's not used. Either remove that function argument or use it to check that sufficient arguments was given. Like:

        p.x = (argc > 1) ? atoi(argv[1]) : 0;
        p.y = (argc > 2) ? atoi(argv[2]) : 0;
    

    Also notice that I removed int x, y; as those variables ain't used.