Thread: Using Malloc inside a function

  1. #1
    Registered User
    Join Date
    Aug 2005
    Posts
    204

    Using Malloc inside a function

    I have written the following code. It initializes an array of size "l," then assigns a value to each element in the array with the function "createArray," and then displays the array with the function "showArray."

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <math.h>
    
    
    
    void createArray(double *array, long *l)
    {	
    	long i;
    	for(i=0; i < *l; i++)
    		array[i]=sin(i/12.0);
    }
    
    
    void showArray(double *array, long l)
    {	
    	long i;
    	for(i=0; i < l; i++)
    		printf("array[%d] = %f \n", i, array[i]);	
    }
    
    
    int main()
    {
    
    	long i, l = 10;
    	double  *array;
    
    	array = malloc(l * sizeof(double));
    	
    	createArray(array, &l);
    	showArray(array, l);
    		
    	exit(0);
    }
    What I would like to do is make the "array = malloc(l * sizeof(double));" statement inside the function "createArray." Something like this:

    Code:
    void createArray(double *array, long *l)
    {	
    	long i;
            array = malloc(*l * sizeof(double));
    	for(i=0; i < *l; i++)
    		array[i]=sin(i/12.0);
    }
    This code runs, but all my numbers are garbage. Any ideas on how I might do this?

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    You need to return a pointer, not just pass the current pointer 'by value'.

    One of
    Code:
    void createArray(double **array, long *l)
    {	
    	long i;
            *array = malloc(*l * sizeof(double));
    	for(i=0; i < *l; i++)
    		(*array)[i]=sin(i/12.0);
    }
    
    // call with
    createArray(&array, &l);
    Code:
    double *createArray(long *l)
    {	
    	long i;
            double *array = malloc(*l * sizeof(double));
    	for(i=0; i < *l; i++)
    		array[i]=sin(i/12.0);
    	return array;
    }
    
    // call with
    array = createArray(&l);
    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. Screwy Linker Error - VC2005
    By Tonto in forum C++ Programming
    Replies: 5
    Last Post: 06-19-2007, 02:39 PM
  2. <Gulp>
    By kryptkat in forum Windows Programming
    Replies: 7
    Last Post: 01-14-2006, 01:03 PM
  3. Change this program so it uses function??
    By stormfront in forum C Programming
    Replies: 8
    Last Post: 11-01-2005, 08:55 AM
  4. Interface Question
    By smog890 in forum C Programming
    Replies: 11
    Last Post: 06-03-2002, 05:06 PM
  5. qt help
    By Unregistered in forum Linux Programming
    Replies: 1
    Last Post: 04-20-2002, 09:51 AM