1
votes

My school assignment states the following i need to create a typedef struct with 2 data type's (Char,Int) ,create 4 elements for it, put these values into an array and print the array. i can manage it up to the point of creating the array. After that it gets a bit fussy for me,

#include <stdio.h>

typedef struct {
    char *Series;
    char KiloWatts;
    int  Age;
} Data_T;

int main(){
     Data_T Motor[4] = {{"B", 3, 2004},{"T", 5, 2005},{"B", 3, 2004},{"A", 2, 2002}}; 
     int i;

     for (i=0; i<4;i++)
         printf("%n", Motor[i]); 
     }

     return 0;
}

I know that the printf right now is not working so is there a function to do this or do i need to write down everything manually?

3
You need to print each member individually or delegate that to a function that does it. - Zoso

3 Answers

3
votes

You need to do the work yourself. One option is this:

 for (i=0; i<4;i++)
     printf("%s %c %d", Motor[i].Series, Motor[i].KiloWatts, Motor[i].Age); 
 }

However, this approach can be quite useful:

void Motor2String(char *dest, Data_T motor) {
    sprintf(dest, "%s %c %d", motor.Series, motor.KiloWatts, motor.Age);
}

And just for clarification. Your array does not have multiple data types. That's not even allowed. What you have is an array where every element is of type Data_T.

2
votes

Unlike other languages, such as C++ with cout and Python with print, C doesn't have a universal "print this" function which knows how to print everything (once you implement the appropriate instance method). So, yes, you would have to print each field manually.

Of course, you can easily set up a function for this. E.g.,

void
print_data(const Data_t *data)
{
    printf("%s, %c, %i\n", data->Series, data->KiloWatts, data->Age);
}
1
votes

There is one way that you could go through, using how it's done in the Linux kernel where there are dedicated *_ops structures to operate on the main struct. These ops structures have function pointers to functions that take in a pointer to the struct. An example for file operations is here. This is the more object-oriented way apparently as this LWN article explains but that's for you to choose if this design makes sense.

So for this case, something like this could work:

#include <stdio.h>

struct Data;

typedef  struct {
    void (*print)(struct Data const* ptr);
}Data_T_ops;

typedef struct Data{
    char *Series;
    char KiloWatts;
    int  Age;
    Data_T_ops const* ops;
}Data_T;

void print_Data_T(Data_T const* ptr) {
    if(ptr) {
        printf("KW: %s\n", ptr->Series);
        printf("%d\n", ptr->Age);
    }
}

static Data_T_ops const data_t_ops = {
    .print = print_Data_T,
};

int main(){
     Data_T Motor[4] = {
         {"B", 3, 2004, &data_t_ops},
         {"T", 5, 2005, &data_t_ops},
         {"B", 3, 2004, &data_t_ops},
         {"A", 2, 2002, &data_t_ops},
    }; 
     int i;
     for (i=0; i<4;i++)
         Motor[i].ops->print(&Motor[i]);
}