Thread: Dynamic array (or something like that) in C

  1. #16
    Registered User
    Join Date
    Dec 2007
    Posts
    30
    Quote Originally Posted by matsp View Post
    In a 32-bit machine, if your key is always 6 chars, you loose 4 bytes per key if you go with the second approach.
    And on 64bit machine ?

    Quote Originally Posted by Banana Man View Post
    Sorry, but I don't want to take over this thread until desmond5 says the original question is answered.
    My question was answered Thankyou If anything comes up, I'll just add to the thread.
    Last edited by desmond5; 03-03-2008 at 01:59 PM.

  2. #17
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Then each pointer would have 8 bytes overhead.

    Quote Originally Posted by Banana Man View Post
    Sorry, but I don't want to take over this thread until desmond5 says the original question is answered. I also think that you're not going to take any of my opinions seriously, so explaining them to you is pointless.
    I don't think you're going to take anyone else's opinions seriously either, since you seem to sneeze at freeing memory, yet as laserlight has already explained it is bad practice.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  3. #18
    Registered User
    Join Date
    Jan 2008
    Posts
    58
    I don't think you're going to take anyone else's opinions seriously either
    I take everyone's opinion seriously. I can't learn if I don't.
    since you seem to sneeze at freeing memory
    I guess it does seem like that with the straw man you've built up. I'm saying that in my program there was no need to free the memory when the program is 1) a simple example, 2) prints something and ends right away, and 3) my OS frees the memory automatically. The reason I said I don't think you're taking me seriously is you keep acting like I'm pushing a practice of never freeing memory, period.

    Anyway, I don't like confrontation, so I'll always free memory in my examples from now on to avoid being attacked. I'll try to conform to the "best practices" you've decided on as I learn what's expected on this board. My deepest apologies for having an independent thought.

  4. #19
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Independent thoughts are good. But your attitude seemed like it was unnecessary.
    I would say it's a requirement, but I can't force anyone to do anything, so what you code for your own is for you to decide, but when posting examples on the board, it's usually better to avoid bad practices.
    Now let's be friends again
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  5. #20
    uint64_t...think positive xuftugulus's Avatar
    Join Date
    Feb 2008
    Location
    Pacem
    Posts
    355
    Whoa it seems like today there were swords drawn. I'd really like to apologize myself for the silly mistake on that other thread with the floating point thing. I was really doing something else at that point and missed a spot.
    Now let's be friends again
    I'll drink to that! As far as i am concerned with memory management, when i learned Java straight after C, i felt like i was flying on the clouds. No free? NO FREE? I AM FREE? But then again, after sometime i started feeling that Java was taking away from me something very precious. So i said: Give me back my MEMORY! It's mine, my own my PRRRREEECCIOUS!!!
    Cheers all! Have a nice day/night whatever.
    Code:
    ...
        goto johny_walker_red_label;
    johny_walker_blue_label: exit(-149$);
    johny_walker_red_label : exit( -22$);
    A typical example of ...cheap programming practices.

  6. #21
    Registered User
    Join Date
    Dec 2007
    Posts
    30
    Quote Originally Posted by Banana Man View Post
    You can do it like this.
    Code:
    #include <stdio.h>
    #include <string.h>
    
    typedef struct
    {
    	char *name;
    	char **keys;
    } row;
    
    int main()
    {
        row temp;
        int i;
    
        temp.name = malloc(50 * sizeof(char));
        strcpy(temp.name, "Banana Man");
    
        temp.keys = malloc(5 * sizeof(char*));
    
        for ( i = 0; i < 5; ++i )
        {
            temp.keys[i] = malloc(3 * sizeof(char));
            memcpy(temp.keys[i], "1234567890" + i, 3);
        }
    
        puts(temp.name);
    
        for ( i = 0; i < 5; ++i )
        {
            int j;
    
            for ( j = 0; j < 3; ++j )
            {
                putchar(temp.keys[i][j]);
            }
    
            putchar('\n');
        }
    
        return 0;
    }
    But what if I wish to add a key after I have already allocated the memory ? Like if I have a function add_key(row *_row, char *key); ? I tried to reallocate but I failed. How would you accomplish that ?

    Best wishes, Desmond5

  7. #22
    uint64_t...think positive xuftugulus's Avatar
    Join Date
    Feb 2008
    Location
    Pacem
    Posts
    355
    Quote Originally Posted by desmond5 View Post
    But what if I wish to add a key after I have already allocated the memory ? Like if I have a function add_key(row *_row, char *key); ? I tried to reallocate but I failed. How would you accomplish that ?

    Best wishes, Desmond5
    The function would need to know the current number of keys stored in the array.
    Code:
    void add_key(row *_row, char *key,int n_keys)
    {
        _row->keys = realloc( (n_keys+1)*sizeof(*_row->keys) );
        if(key!=NULL)
        { 
            _row->keys[n_keys] = malloc(3 * sizeof(char));
            memcpy(_row->keys[n_keys], key, 3);
        } else {
            _row->keys[n_keys] = NULL;  
    }
    Code:
    ...
        goto johny_walker_red_label;
    johny_walker_blue_label: exit(-149$);
    johny_walker_red_label : exit( -22$);
    A typical example of ...cheap programming practices.

  8. #23
    Registered User
    Join Date
    Dec 2007
    Posts
    30
    Quote Originally Posted by xuftugulus View Post
    The function would need to know the current number of keys stored in the array.
    Code:
    void add_key(row *_row, char *key,int n_keys)
    {
        _row->keys = realloc( (n_keys+1)*sizeof(*_row->keys) );
        if(key!=NULL)
        { 
            _row->keys[n_keys] = malloc(3 * sizeof(char));
            memcpy(_row->keys[n_keys], key, 3);
        } else {
            _row->keys[n_keys] = NULL;  
    }
    Yeah..but it gives a warning "[Warning] assignment makes pointer from integer without a cast" on this line: _row->keys = realloc( (n_keys+1)*sizeof(*_row->keys) );

  9. #24
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    You are missing proper #include
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

  10. #25
    Registered User
    Join Date
    Dec 2007
    Posts
    30
    Really ? I don't know what else I need to include..

    Code:
    #include <stdio.h>
    #include <string.h>
    
    typedef struct
    {
    	char *name;
    	char **keys;
    } row;
    
    void add_key(row *_row, char *key, int n_keys, int columns)
    {
        _row->keys = realloc( (n_keys+1)*sizeof(*_row->keys) );
        if(key!=NULL)
        {
            _row->keys[n_keys] = malloc(columns * sizeof(char));
            memcpy(_row->keys[n_keys], key, columns);
        }
    	else
    	{
            _row->keys[n_keys] = NULL;
    	}
    }
    
    int main()
    {
        row temp;
        int i = 0;
    
        int n_keys = 0;
    
        int rows = 10;
        int columns = 5;
    
        temp.keys = malloc(rows * sizeof(char*));
    
    	add_key(&temp, "somekey", n_keys, columns);
    
    
        for ( i = 0; i < rows; ++i )
        {
            int j;
    
            for ( j = 0; j < columns; ++j )
            {
                putchar(temp.keys[i][j]);
            }
    
            putchar('\n');
        }
    
    	getchar();
        return 0;
    }

  11. #26
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    You should use the <stdlib.h> include for the malloc/realloc calls.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  12. #27
    Ex scientia vera
    Join Date
    Sep 2007
    Posts
    477
    Quote Originally Posted by matsp View Post
    You should use the <stdlib.h> include for the malloc/realloc calls.

    --
    Mats
    And to pick up on those errors, you just include some warning flags.

    If you're using gcc or mingw, -Wall and -ansi is enough I believe.

    Note that the errors won't say "You forgot header file x", but rather something like "Implicit declaration of function x" when you try and call a function that hasn't been explicitly declared anywhere, but is still being implicitly declared to exist when you call it.

  13. #28
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Quote Originally Posted by IceDane View Post
    And to pick up on those errors, you just include some warning flags.

    If you're using gcc or mingw, -Wall and -ansi is enough I believe.

    Note that the errors won't say "You forgot header file x", but rather something like "Implicit declaration of function x" when you try and call a function that hasn't been explicitly declared anywhere, but is still being implicitly declared to exist when you call it.
    Indeed.

    Also note that it's good practice to include header files that you KNOW you need, even if the compiler doesn't complain about them - for example you may find that stdio.h or string.h included stdlib.h IN YOUR case, but using a different set of header files (belonging to a different compiler or C library) the includes done by those header files DO NOT include stdlib.h - thus making it fail on a different system.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  14. #29
    uint64_t...think positive xuftugulus's Avatar
    Join Date
    Feb 2008
    Location
    Pacem
    Posts
    355
    Sorry for the type damn it!
    ...
    Code:
        _row->keys = realloc(_row->keys, (n_keys+1)*sizeof(*_row->keys) );
    Add the blue thing to the function.

    void *realloc(void *p, size_t new_size):
    where p must be either a pointer, previously initialized with malloc, or calloc or NULL.
    It is necessary to store the return of realloc to the previously allocated pointer as it might return a different address, not enough continual memory to satisfy the request will force a clone of the previously allocated area to a new memory section.

    When including the <stdlib.h> header, it shouldn't compile without correcting it.
    Code:
    ...
        goto johny_walker_red_label;
    johny_walker_blue_label: exit(-149$);
    johny_walker_red_label : exit( -22$);
    A typical example of ...cheap programming practices.

  15. #30
    Registered User
    Join Date
    Dec 2007
    Posts
    30
    Many thanks

    One more thing..I add three elements to the array. How is it that it has 4 ? I even cannot access the fourth element..

    Code:
    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    
    typedef struct
    {
    	char *name;
    	char **keys;
    } row;
    
    void add_key(row *_row, char *key, int n_keys, int columns)
    {
    	if (n_keys == 0) _row->keys = malloc(sizeof(char*));
    	else _row->keys = realloc(_row->keys, (n_keys+1)*sizeof(*_row->keys) );
    
        if(key!=NULL)
        {
            _row->keys[n_keys] = malloc(columns * sizeof(char));
            memcpy(_row->keys[n_keys], key, columns);
        }
    	else
    	{
            _row->keys[n_keys] = NULL;
    	}
    }
    
    int main()
    {
        row temp;
        int i = 0;
    
        int n_keys = 0;
    
        int rows = 10;
        int columns = 5;
    
    	add_key(&temp, "key0", 0, columns);
    	add_key(&temp, "key1", 1, columns);
    	add_key(&temp, "key2", 2, columns);
    
    	double si = sizeof(temp.keys);
    
        printf("%s\n", temp.keys[0]);
        printf("%s\n", temp.keys[1]);
        printf("%s\n", temp.keys[2]);
    
           //printf("%s\n", temp.keys[3]); doesnt excist ?
    
    
        printf("Size: %lf", si); // PRINTS 4 not 3 as expected
    
    	getchar();
        return 0;
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Dynamic Array Resizing
    By dld333 in forum C++ Programming
    Replies: 13
    Last Post: 11-04-2005, 12:13 AM
  2. need help with dynamic array syntax
    By soldyne in forum C Programming
    Replies: 3
    Last Post: 10-11-2005, 01:59 PM
  3. Class Template Trouble
    By pliang in forum C++ Programming
    Replies: 4
    Last Post: 04-21-2005, 04:15 AM
  4. 2D dynamic array problem
    By scsullivan in forum C Programming
    Replies: 3
    Last Post: 12-30-2002, 10:02 PM
  5. Dynamic array allocation and reallocation
    By purple in forum C Programming
    Replies: 13
    Last Post: 08-01-2002, 11:48 AM