是否可以在同一代码中使用两个不同的结构?

时间:2019-02-12 11:03:49

标签: c

我需要在代码中添加另一个结构,我想知道是否可行? 以下是我想做什么的摘要。

#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include "math.h"
#define MAX_CARS 10

struct car {
  double vel, position, desired_vel;
  int index, on_network;
};
typedef struct car Car;

struct car_2 {
  double vel_2, position_2, desired_Vel_2;
  int index, on_network;
};

typedef struct car_2 Car_2;

3 个答案:

答案 0 :(得分:5)

您的代码中可以有无限个结构类型。不过,在这种情况下,由于它们是相同的,因此您可以重复使用Car结构并为其创建单独的实例。

Car car1;
Car car2;
car1.vel = 5.0;
car2.vel = 10.0;

答案 1 :(得分:0)

是的,您可以使用任意多个。示例代码如下:

#include <stdio.h>
struct car_dim
{
    int feet;
    float inch;
} card;

struct showroom_loc
{
    int lid;
    int pin;
} carl;

int main()
{
    printf("enter the information for card struct\n");

    printf("Enter feet: \n");
    scanf("%d", &card.feet);

    printf("Enter inch: \n");
    scanf("%f", &card.inch);

    printf("enter the information for car location struct\n");

    printf("enter lid e\n");    
    scanf("%d", &carl.lid);

    printf("Enter pin: \n");
    scanf("%f", &carl.pin);

    printf("struct card= %d\'-%.1f\"", card.feet, card.inch);        
    printf("\nstruct carl= %d\'-%.1f\"", carl.lid, carl.pin);
    return 0;
}

答案 2 :(得分:0)

只要名称不同,您就可以在代码中根据需要使用许多结构

但是在您的示例中,结构的成员是相同的,也许您想要执行类似的操作?

#define MAX_CARS 10

struct car {
    double vel, position, desired_vel;
    int index, on_network;
};
typedef struct car Car;

int main() {

    // You can define as many instances of type "Car" as you want
    Car car1;
    Car car2;
    Car car3;

    // Or you can use arrays
    Car cars[MAX_CARS];

    cars[0].desired_vel = 100.0;
    cars[1].desired_vel = 120.0;
    // and so on

    return 0;
}