Thread: c dynamic arrays

  1. #1
    unregistered
    Guest

    c dynamic arrays

    i would like to dynamically allocate a char array on the fly,
    that is have: char *string; and use getch() to put in characters one at a time and allocate memory as this is happening.

  2. #2
    Unregistered
    Guest
    Do you have an attempt? Post a little code, and we'll go from there.

  3. #3
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    Assuming that the variable n is the number of elements you want the array to be:
    Code:
    char *array;
    if ( ( array = malloc ( n * sizeof *array ) ) != NULL ) {
      /* Now you have an array to work with
      */
    }
    else {
      /* Oops, it didn't work so now you have to
      ** clean up after yourself or try again.
      */
    }
    -Prelude
    My best code is written with the delete key.

  4. #4
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,708
    Actually, realloc() is what your looking for...

    Problem is, how do you know when to exit the getch() loop?!
    Code:
    #include <cmath>
    #include <complex>
    bool euler_flip(bool value)
    {
        return std::pow
        (
            std::complex<float>(std::exp(1.0)), 
            std::complex<float>(0, 1) 
            * std::complex<float>(std::atan(1.0)
            *(1 << (value + 2)))
        ).real() < 0;
    }

  5. #5
    Registered User
    Join Date
    May 2002
    Posts
    4
    So, is it possible to use a normal array and use a variable for an array size to make it dynamic (or just an array that dynamically changes size), or do you have to start messing around with pointers to achieve that stuff.

    e.g.

    int n;

    int array[n];

    ???

  6. #6
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    > is it possible to use a normal array and use a variable for an array size to make it dynamic
    Only in the latest C99 standard
    There are not too many compilers which support this yet - though I think gcc is pretty close.

    > do you have to start messing around with pointers to achieve that stuff
    For now, yes

  7. #7
    Registered User
    Join Date
    May 2002
    Posts
    4

    Exclamation

    Thanks for that,

    and Bugger,

    So is it still possible to use a dynamic array with a struct ?

    e.g.
    struct structy
    {
    int quantity;
    int date;
    }

  8. #8
    Registered User
    Join Date
    May 2002
    Posts
    4

    Exclamation

    Thanks for that,

    and Bugger,

    So is it still possible to use a dynamic array with a struct ?

    e.g.
    struct structy
    {
    int quantity;
    int date;
    }

    structy record[5];

    How could you do something like that in a dynamic format?

    Any help would much appreciated...!

  9. #9
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    Yes, just follow Prelude's example

  10. #10
    Registered User
    Join Date
    May 2002
    Posts
    4
    Sorry about that,

    I accidently posted twice...

  11. #11
    Registered User
    Join Date
    May 2002
    Posts
    14
    i would like to dynamically allocate a char array on the fly,
    that is have: char *string; and use getch() to put in characters one at a time and allocate memory as this is happening.
    like this
    Code:
    #include     <stdio.h>
    #include     <conio.h>
    #include     <stdlib.h>
    int main()
        {
        char*str;
        int i=0;
    
        string=calloc(i,sizeof(char));
        while(str=realloc(str,i+1),str[i]=getche()!='\r')
            {
            i++;
            }
        str[i]='\0';
        printf("\n%s\n",str);
        }

  12. #12
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    Code:
    #include     <stdio.h>
    #include     <conio.h>
    #include     <stdlib.h>
    int main()
        {
        char*str;
        int i=0;
    
        string=calloc(i,sizeof(char));
        while(str=realloc(str,i+1),str[i]=getche()!='\r')
            {
            i++;
            }
        str[i]='\0';
        printf("\n%s\n",str);
        }
    This code doesn't work:
    input:
    >aaaaaaaaaaaa
    Output:
    >
    That's after I fixed the variable called string (renamed it to str).

    There's a lot of potential for problems too. (no checking that the alloc calls worked etc)

    I don't have time to rewrite it, maybe someone else will.
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

  13. #13
    Registered User
    Join Date
    May 2002
    Posts
    14
    This code doesn't work:
    your right. i fixed it though
    Code:
    #include     <stdio.h>
    #include     <conio.h>
    #include     <stdlib.h>
    int main()
        {
        char*str;
        int i=0;
    
        str=calloc(i,sizeof(char));
       while(str=realloc(str,i+1),(str[i]=getche())!='\r')
            {
            i++;
            }
        str[i]='\0';
        printf("\n%s\n",str);
        }

  14. #14
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    You should always check the return from malloc, calloc and realloc etc. If there's a memory problem, they'll return NULL, which can be particularly bad in your example of realloc().

    >str = realloc(str, i + 1)
    Here, str is both passed to the function, and used to catch the return.
    If realloc fails to get new memory, it will return NULL, but it will not *loose* the memory that is already being pointed to by str.
    But, because str gets the returning NULL, you loose the pointer to the old memory area.

    A safer way to do this is to set the return to a temp variable, check it for NULL, then assign it to str if all is OK.
    Code:
    /* but down sample */
    char	*str, *tmp;
    	int i = 1;
    
    	if ((str = calloc(i, sizeof(char))) == NULL)
    	{
    		perror ("calloc");
    		return (1);
    	}
    	
    	/* more code */
    	i += 10;
    	if ((tmp = realloc(str, i + 1)) == NULL)
    	{
    		perror ("realloc");
    		return (1);
    	}
    	str = tmp; /* all OK, so reassign pointer */
    
    	printf ("%s\n", str);
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Creating and freeing dynamic arrays
    By circuitbreaker in forum C++ Programming
    Replies: 8
    Last Post: 02-18-2008, 11:18 AM
  2. Replies: 16
    Last Post: 01-01-2008, 04:07 PM
  3. processing dynamic arrays
    By Mario F. in forum C++ Programming
    Replies: 9
    Last Post: 06-04-2006, 11:32 AM
  4. Dynamic (Numeric) Arrays
    By DavidB in forum C++ Programming
    Replies: 5
    Last Post: 05-03-2006, 07:34 PM