Thread: Malloc in Array of Structures

  1. #1
    Registered User
    Join Date
    Dec 2020

    Post Malloc in Array of Structures

    I have a homework about coding a car saler program. User gives us the datas about cars as a string so I should use strtok and atoi.

    struct ilanBilgi {    char sehir[15];
        int fiyat;
        struct ilanTarih;
        char marka[15];
        char model[15];
        int modelYil;
    These are the datas about cars and I should locate memory for 5 cars for the beginning if user keeps entrying data I should locate memory for another 5 so it goes like 5 cars,10 cars,15,20...

    What should I do with the malloc functions?

  2. #2
    Programming Wraith GReaper's Avatar
    Join Date
    Apr 2009
    They way I do it is to have two variables, one for the allocated size and another for the used size. When the used size equals the allocated size, it's time to allocate new memory.
    Devoted my life to programming...

  3. #3
    Registered User
    Join Date
    Dec 2020
    Okay thanks for your help but can you show me how should I use the malloc and realloc functions?

  4. #4
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    The edge of the known universe
    struct ilanBilgiVector {
        struct ilanBilgi *data;
        size_t allocated;
    void init ( struct ilanBilgiVector *v ) {
      v->data = NULL;
      v->allocated = 0;
    void extend ( struct ilanBilgiVector *v ) {
      size_t new_size = v->allocated * 2;
      if ( new_size == 0 ) new_size = 16;
      struct ilanBilgi *ptr = realloc( v->data, sizeof(*v->data) * new_size );
      if ( ptr ) {
        v->data = ptr;
        v->allocated = new_size;
      } else {
        // v->data is still valid, but there's no more room for more data
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 2
    Last Post: 04-17-2015, 05:50 PM
  2. Replies: 1
    Last Post: 04-17-2015, 04:29 PM
  3. Help with malloc and structures?
    By ZAxel in forum C Programming
    Replies: 1
    Last Post: 12-06-2011, 04:11 PM
  4. malloc() with array of structures
    By khpuce in forum C Programming
    Replies: 8
    Last Post: 10-26-2010, 07:12 AM
  5. malloc ing array's or structures
    By Markallen85 in forum C Programming
    Replies: 4
    Last Post: 02-03-2003, 01:23 PM

Tags for this Thread