C语言 返回类型时不兼容的类型

jbose2ul  于 2023-03-29  发布在  其他
关注(0)|答案(2)|浏览(206)

我在convertToPoint函数上遇到问题。

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

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

  return p;
}

期望返回类型为point的结构,但收到以下错误:
错误:返回类型“struct point”时类型不兼容,但应返回“int”p;
有什么问题吗?

kgsdhlau

kgsdhlau1#

这是一个非常简单的问题,你说你想返回一个struct point,但是你的代码说这个函数应该返回int

int convertToPoint(
^^^
ups, shall return int

因此,只需将其更改为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);
}

也就是说-在不使用argc的情况下传递它有点奇怪。要么删除该函数参数,要么使用它来检查是否提供了足够的参数。例如:

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

还请注意,我删除了int x, y;,因为这些变量没有使用。

0md85ypi

0md85ypi2#

麻烦的是你告诉编译器你返回的是一个int,你想要说struct point convertToPoint(...)
您看到的错误消息告诉您这一点,如果您知道如何解析它的话
error: incompatible types when returning type ‘struct point’ but ‘int’ was expected return p;

  1. return p;-〉这是编译器可以分辨的麻烦语句。
  2. incompatible types when returning-〉您返回了错误的内容,请检查您返回的内容以及签名是什么
  3. type ‘struct point’-〉这是您在body中返回的内容
  4. but ‘int’ was expected-〉这是来自函数签名的值。
    下面是一个完整的例子
// convert.c
#include <stdio.h>
#include <stdlib.h>

struct point {
  int x;
  int y;
};

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

  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", p.x, p.y);
}

证明它有效

~/src ❯❯❯ gcc -ansi convert.c -o convert                                                                                                                                               ✘ 139 
~/src ❯❯❯ ./convert 1 2
1, 2%

最后,您可以做一点重构来清理这一点

// convert.c
#include <stdio.h>
#include <stdlib.h>

struct point {
  int x;
  int y;
};

struct point convertToPoint(char x[], char y[]) {
  struct point p;

  p.x = atoi(x);
  p.y = atoi(y);

  return p;
}

int main(int argc, char** argv) {
    //TODO: check for 2 args and print a helpful error message
    struct point p = convertToPoint(argv[0], argv[1]);
    printf("%d, %d", p.x, p.y);
}

相关问题