问题是你告诉编译器你返回一个int 和int convertToPoint(...)。你想说struct point convertToPoint(...)
如果您知道如何解析它,您看到的错误消息会告诉您这一点
error: incompatible types when returning type ‘struct point’ but ‘int’ was expected return p;
return p; -> 就编译器而言,这是个麻烦的语句。
incompatible types when returning -> 你返回了错误的东西,检查你返回的是什么以及签名是什么
type ‘struct point’ -> 这是你在体内返回的东西
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);
}