2

I have these 2 structs :

typedef struct {
    char name[20];
    int num;
    int score;
} player;

typedef struct {
    char name[20];
    player *players;
} team;

I need to know the amount of elements stored per every *players inside my team struct. Thanks!

4
  • 2
    Then create a struct member for that (of type size_t, perhaps). Commented Apr 21, 2013 at 19:55
  • The team struct just contains a pointer to a player. This could be the first player in an array of players or it could just be a single player. How many will depend on how many you allocate when you assign some memory to that pointer. Commented Apr 21, 2013 at 19:56
  • @Will, i alocate 22, but the program may or may not use 22, so, then I'll realloc that memory to the amount used, then, a function needs to print how many players there are per team, so, i need a way to know how many items there're in the array itself Commented Apr 21, 2013 at 20:08
  • 1
    possible duplicate of How to find the 'sizeof'(a pointer pointing to an array)? Commented Apr 21, 2013 at 21:01

1 Answer 1

7

You can't. players is a pointer to N player instances. It carries no more information than an address. It is not an array; it is a pointer.

You will have to store the number of elements in the struct separately.

typedef struct {
    char name[20];
    player *players;
    size_t num_players;
} team;

On a side note, you had better hope that Jarrod Saltalamacchia never joins this team.

Sign up to request clarification or add additional context in comments.

8 Comments

That side note! (I'd +1 this if I had any votes left for today.)
Jarrod Saltalamacchia?? Who is that and why does he suck?
@LefterisE: char name[20];
@H2CO3: Damn it all, I was editing! :D I actually tried to find a name that was 20, but 21 was the best I could do.
the names are max 20 chars by specs, not my decission. When all works i'll change that to char *name and make it work properly, untill then, i just want it working
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.