Thread: help with malloc

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

    help with malloc

    Hello all... I have a test upcoming on Malloc and was wondering if you could answer some questions for me.


    do I need to call malloc for each instance that I want to store a string into a 2 dimensional array or can i just use realloc?

    like for instance if i have a loop collecting strings into a 2 dimensional array and i call malloc to a certain "buffer" size outside of the loop, will i only need to call it once? i understand that i can use realloc to resize the buffer to the size of the largest line in the array. but would i need to use a temp[] array to store the current string then find its strlen and if that string is the largest line use realloc to resize the buffer?

    was wondering if anyone could write some dummy code demonstrating the above... if not maybe just an explanation would be fine. Thanks all... =)

    oh if you know any webpages that have good detailed examples of malloc that would be great because my book really sucks.

    GT
    [email protected]

  2. #2
    Banned Troll_King's Avatar
    Join Date
    Oct 2001
    Posts
    1,784
    Code:
    #include<stdio.h>
    #include<string.h>
    #include<stdlib.h>
    
    int main()
    {
    	char **array; //2d array of size array[rows][columns]
    	int i; //index
    	int rows = 2, columns = 6;
    
    	//allocate memory
    	array = (char **) malloc (sizeof (char*) * rows);
    	for(i=0;i < rows;i++)
    		array[i] = (char *) malloc (sizeof(char) * columns);
    	
    	strcpy(array[0],"Hello");
    	strcpy(array[1],"World");
    
    	for(i = 0; i < rows; i++)
    		printf("Array[rows] = %s\n",array[i]);
    
    	//release memory
    	for(i=0;i<rows;i++)
    		free(array[i]);
    	
    	return 0;
    }
    Does this help son?

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. malloc + segmentation fault
    By ch4 in forum C Programming
    Replies: 5
    Last Post: 04-07-2009, 03:46 PM
  2. Is there a limit on the number of malloc calls ?
    By krissy in forum Windows Programming
    Replies: 3
    Last Post: 03-19-2006, 12:26 PM
  3. Malloc and calloc problem!!
    By xxhimanshu in forum C Programming
    Replies: 19
    Last Post: 08-10-2005, 05:37 AM
  4. malloc and realloc
    By odysseus.lost in forum C Programming
    Replies: 3
    Last Post: 05-27-2005, 08:44 AM
  5. malloc() & address allocation
    By santechz in forum C Programming
    Replies: 6
    Last Post: 03-21-2005, 09:08 AM