c - 将函数的返回值存储为 C 中的结构体数组
问题描述
我有一个函数可以打印出二次函数 ax^2 + bx + c 的 11 个点,输入为 a、b、c。该函数工作正常,除了我需要使用结构,而不仅仅是变量 x 和 y。如何让我的函数返回结构值并将其存储在结构数组中,然后打印出结构数组?
struct point {
int x;
int y;
};
struct point *findpoint(int a, int b, int c){
int i, x, y;
x = -5;
for (i = 0; i < 11; i++)
{
y = (a * (x * x)+ (b * x) + c);
printf("The points are {%d, %d}\n", x, y);
x++;
}
}
struct point arr_point[11];
int main(int argc, char *argv[]){
struct point *ptr;
printf("Enter coefficients a, b, c:");
int a, b, c;
int i;
for (i = 0; i < argc; i++){
scanf("%d %d %d", &a, &b, &c);
}
printf("%d %d %d\n", a, b, c);
findpoint(a, b, c);
return 0;
}
解决方案
您可以使用以下命令为您的结构创建别名typedef
:
typedef struct {
int x;
int y;
} Foo_t;
Foo_t returnStruct() {
Foo_t foo = {1,2};
return foo;
}
int main() {
const uint8_t SIZE_ARRAY = 2;
Foo_t arrayFoo[SIZE_ARRAY];
arrayFoo[0] = returnStruct();
arrayFoo[1] = returnStruct();
for(uint8_t i=0;i<SIZE_ARRAY;i++) {
printf("Index %d: x=%d y=%d \n", i, arrayFoo[i].x, arrayFoo[i].y);
}
}
推荐阅读
- ios - 检查保存到相机胶卷是否成功
- django - 尽管路径正确,但 django 中的静态文件不起作用(404)
- java - 如何在 Java Swing 中更改日期
- anylogic - 如何将 String 类型转换为 ConveyorPath 类型?
- javascript - 如何通过 API 修补 Azure Devops 上的测试结果
- vim - 如何在 Vim 中通过 *.log 中的路径打开另一个文件
- c# - c# NPOI Excel设置页码
- nginx - 通过 NGINX 替换请求参数中的指定字符
- ontology - OWL本体的可扩展性(是大还是小)
- android - 获取已安装应用列表