Reputation: 33
I've declared an array of structs as so:
typedef struct{
int source;
int dest;
int type;
int port;
char data;
}test;
test packet[50];
and I'm trying to access the array and print it to the screen as such:
for (p = 0; p < i; p++)
{
printf("%i", packet[p]);
}
But I'm not getting what I expect. I'm very new at C so I'm sorry for any problems with this post. Just ask for more information and I'll give it. Have I got the logic completely wrong with this?
In my head I've created an 50 instances of the struct in an array with each element of the array containing the 5 variables in the struct.
Upvotes: 0
Views: 128
Reputation: 7102
It's been ages since I've done C but I don't think it works that way. You might want to print the struct's member variables one by one.
for (p = 0; p < i; p++)
{
printf("%i\n", packet[p].source);
printf("%i\n", packet[p].dest);
printf("%i\n", packet[p].type);
printf("%i\n", packet[p].port);
}
Or better yet, make a method, call it something like printTest()
and have it do the above.
In your example above, you're trying to print the whole object, which wouldn't work.
Upvotes: 3
Reputation: 10695
Given
typedef struct{
int source;
int dest;
int type;
int port;
char data;
}test;
test packet[50];
your must explicitly reference each and every field you want to access. In the case of your example, you wish to print each field of the structure, so you will need to refer specifically to each field, like this: printf("%i\n", packet[0].source);
Your specific example was in a for loop with p as the array index, so the actual code would be printf("%i\n", packet[p].source);
Finally, you can easily discuss some C constructs in C++, but not C++ constructs, like classes, in C.
Upvotes: 0