【问题标题】:Returing structure values back to main() from function()从 function() 将结构值返回给 main()
【发布时间】:2018-03-13 20:20:36
【问题描述】:

再次需要帮助。用户在 docreate() 函数中输入了一些值,我需要将这些值返回到主函数中来打印它们。我已经尝试但无法实现目标。当用户在主代码中输入 2 时,我现在只是无人机(名称)的一个特征,用于打印。代码如下:

#include <stdlib.h>
#include <string.h>
#include <stdio.h>

struct drone_t{
    char name[30];
    float top_s;
    float acc;
};

struct do_create(int dronesCreated);

#define MAXDRONES 3

int main()
{
    struct drone_t drone; 
    int dronesCreated = 0;
    int i;
    char namee;
    while(1)
    {
        printf("1. Create Drone\n2. Calculate Time\n3. Exit\n");
        scanf("%d", &i);
        if (i == 1)
        {
            if(dronesCreated<=MAXDRONES-1)
            {
                dronesCreated++;
                do_create(dronesCreated);
            }
            else
            {
                printf("error: cannot create more drones\n");
            }
        }
        else if (i == 2)
        {
            printf("%s", drone[dronesCreated].name);
        }
        else if (i == 3)
        {
            exit(EXIT_SUCCESS);
        }
        else
        {
            printf("error: select an option between 1 and 3\n");
        }
    }
}

void do_create(int dronesCreated)
{

    struct drone_t drone[dronesCreated];
    printf("What is the name of the drone?\n");
    scanf("%s", drone[dronesCreated].name);
    printf("What is the top speed of the drone? (kmph)\n");
    scanf("%f", &drone[dronesCreated].top_s);
    printf("What is the acceleration of the drone? (mpsps)\n");
    scanf("%f", &drone[dronesCreated].acc);
    return drone.name;
}

【问题讨论】:

  • struct do_create(int dronesCreated); - 不是任何有效的声明。
  • 它是 void do_create (intdronesCreated);之前。我将其更改为移动值,但无论如何它都不起作用。
  • 数组必须在main中定义。如果函数的返回类型为void,则不能返回值。
  • 我在这方面遇到了困难,你能提供一个关于如何做到这一点的行或示例吗?
  • 示例code

标签: c arrays function pointers structure


【解决方案1】:

您的代码几乎没有错误,如下修复它们可能会给您想要的结果:

  1. struct do_create(int dronesCreated); 是无效声明,应为 void do_create(int dronesCreated);
  2. 你在main中使用了drone变量作为一个数组,但是它被声明为drone_t结构,所以它应该被声明为一个数组,如下:struct drone_t drone[MAXDRONES];
  3. char namee; 从未使用过,应该删除或使用
  4. C 中的数组索引为 0,但 dronesCreated 索引在第一个 if 语句中被初始化为 0 并递增 1,因此它将从 1 而不是 0 开始。因此,您必须使用 -1 对其进行初始化当在 if 语句中递增 1 时,它将从索引 0 开始,或者您必须在调用 do_create 后递增它
  5. do_create 被声明为 void 但您正在尝试返回一些值(在您的情况下为 char*),因此您可以将其更改为返回 struct drone_t
  6. do_create 内重新定义main 中定义的struct drone_t drone[dronesCreated],注意do_create 中的drone 变量将是在clsoest 范围内定义的drone,它是局部变量,修改它不会影响 main 中定义的那个。因此,您要么必须将其定义为全局变量,将其作为参数传递给do_create,要么让do_create 将新的struct drone_t 返回给main,并在main 中将其分配到drone 数组中。李>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-02-17
    • 1970-01-01
    • 2014-12-28
    • 2023-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多