Thread: arrays with malloc

  1. #1
    Registered User
    Join Date
    Oct 2001
    Posts
    104

    arrays with malloc

    How do I create dynamically arrays using malloc???

    In C++ it's :

    int count;
    count=40;

    char *array;
    array=new array[count];


    but how it is in C????

    Thank you in advance!
    Ilia Yordanov,
    http://www.cpp-home.com ; C++ Resources

  2. #2
    Banned Troll_King's Avatar
    Join Date
    Oct 2001
    Posts
    1,784
    For a 2d array:

    Code:
    #include<stdio.h>
    #include<stdlib.h>
    
    int main()
    {
    	char **iptr = (char **) malloc (sizeof(char*) * 3);
    	for(int i = 0;i < 3; i++)
    		iptr[i] = (char *) malloc (sizeof(char) * 10);
    
    	strcpy(iptr[0], "Chicken");
    	strcpy(iptr[1], "Cow");
    
    	printf("%s  %s", iptr[0],iptr[1]);
                        for(i=0;i<3;i++)
                                   free(iptr[i]);
    	return 0;
    }
    The format is off because I cut and pasted part of it and than tried to type other parts.

    For a normal array
    Code:
    char *array = (char *) malloc (sizeof(char) * 20);
    The array is the same as
    char array[20];
    Last edited by Troll_King; 10-15-2001 at 01:16 PM.

  3. #3
    Registered User
    Join Date
    Oct 2001
    Posts
    104
    Thank you a lot Troll_King!!! It worked!!!!!!
    Ilia Yordanov,
    http://www.cpp-home.com ; C++ Resources

  4. #4
    Banned Troll_King's Avatar
    Join Date
    Oct 2001
    Posts
    1,784
    Yeah the 2d array would be the same as:

    char iptr[3][10];

    It's all about rows and columns. You could do this:

    char iptr[rows][columns];

    char **iptr = (char **) malloc (sizeof(char*) * ROWS);
    for(int i = 0;i < ROWS; i++)
    iptr[i] = (char *) malloc (sizeof(char) * COLUMNS);

    Ofcourse you would need to give the sizes of the rows and columns. This is the format however.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Structures, arrays, pointers, malloc.
    By omnificient in forum C Programming
    Replies: 9
    Last Post: 02-29-2008, 12:05 PM
  2. Confused about malloc and arrays
    By mc61 in forum C Programming
    Replies: 5
    Last Post: 01-15-2008, 06:22 PM
  3. Large arrays, malloc, and strcmp
    By k2712 in forum C Programming
    Replies: 1
    Last Post: 09-24-2007, 08:22 PM
  4. malloc for structs and arrays
    By rkooij in forum C Programming
    Replies: 15
    Last Post: 05-04-2006, 07:38 AM
  5. malloc ing array's or structures
    By Markallen85 in forum C Programming
    Replies: 4
    Last Post: 02-03-2003, 01:23 PM