Array of structs in C

后端 未结 5 1592
执笔经年
执笔经年 2021-01-05 23:33

I\'m trying to create an array of structs and also a pointer to that array. I don\'t know how large the array is going to be, so it should be dynamic. My struct would look s

相关标签:
5条回答
  • 2021-01-06 00:15

    The second option of a pointer is good.

    If you want to allocate things dynamically, then try:

    stats_t* theStatsPointer = (stats_t*) malloc( MAX * sizeof(stats_t) );
    

    as Roland suggests.

    Just don't forget to

    free(theStatsPointer);
    

    when you're done.

    0 讨论(0)
  • 2021-01-06 00:15

    Use malloc():

    http://en.wikipedia.org/wiki/Malloc

    0 讨论(0)
  • 2021-01-06 00:20

    This is how it is usually done:

    size_t n = <number of elements needed>
    stats_t *ptr = malloc (n * sizeof (stats_t));
    

    Then, to fill it in,

    for (size_t j = 0;  j < n;  ++j)
    {
       ptr [j] .hours = whatever
       ptr [j] .days = whatever
       ...
    }
    
    0 讨论(0)
  • 2021-01-06 00:25

    Based on your replies to other answers it looks like you need a dynamic data structure like a linked list. Take a look at the queue(3) set of facilities.

    0 讨论(0)
  • 2021-01-06 00:35

    malloc is your friend here.

    stats_t stats[] = (stats_t*)malloc(N * sizeof(stats_t));
    

    stats sort of is a pointer to the array. Or you can use stats[3] syntax as if it were declared explicitly as an array.

    0 讨论(0)
提交回复
热议问题