Like Tree5Likes

Dynamic Allocating Array and Function Call

This is a discussion on Dynamic Allocating Array and Function Call within the C Programming forums, part of the General Programming Boards category; I am baring with you Sorinx Everybody has been in your situation, so no problem You have Code: for ( ...

  1. #16
    SAMARAS std10093's Avatar
    Join Date
    Jan 2011
    Location
    Nice, France
    Posts
    2,675
    I am baring with you Sorinx Everybody has been in your situation, so no problem

    You have
    Code:
     for (j=0;i<NUMBER_OF_GRADES;j++)
    So you play with counter j, but you use counter i too. Counter i for another for loop, not for this!
    So you should play only with counter j in this loop

    So replace that with this
    Code:
     for (j=0;j<NUMBER_OF_GRADES;j++)
    Code - functions and small libraries I use


    It’s 2014 and I still use printf() for debugging.


    "Programs must be written for people to read, and only incidentally for machines to execute. " —Harold Abelson

  2. #17
    Registered User
    Join Date
    Oct 2012
    Posts
    126
    Ahh yes, I noticed that and changed it, I can enter the inputs, but then afterwards it crashes.

  3. #18
    SAMARAS std10093's Avatar
    Join Date
    Jan 2011
    Location
    Nice, France
    Posts
    2,675
    It crashed in the function of the average.

    In main, when you were filling the array you said
    Code:
    for(student=0; student<NUMBER_OF_STUDENTS; student++)
        {//for loop for populating 3 dimensional array
            for(class=0;class<NUMBER_OF_CLASSES;class++)
                {
         
            for(grade=0; grade<NUMBER_OF_GRADES; grade++)
                {
                if(grade==0){
                    printf("Enter in the grade for student %d in subject %d:\n", student+1, class+1);
                    scanf("%d", &array[student][class][grade]);
                }else
                    scanf("%d",&array[student][class][grade]);
    }
    }
    }
    So you went through every single cell of your array.

    Now in the average function you want to get the value of every single cell and add it to the sum.

    Here is your function
    Code:
    float gradeAve(int ***c)
    {
      float sum=0;
        int grade;//local variables
     
            for(grade=0; grade<NUMBER_OF_GRADES; grade++)
            {
                sum+=c[NUMBER_OF_STUDENTS][NUMBER_OF_CLASSES][NUMBER_OF_GRADES];//only takes sum of the grades and divides by number of grades
            }
         
        return (sum/NUMBER_OF_GRADES);
     
    }
    You have a 3D array and only one counter. This usually is wrong.

    Think simple. Let's say we have a single int array of 5 elements.
    Code:
    int N = 5;
    int array[N];
    and then you want to access an element and you say
    Code:
    printf("%d\n",array[N]);
    As you know matrices start counting from zero, thus the last element is in position N-1.
    So if you say array[N] you access memory that is not yours. <--ERROR

    This is pretty much what you do in the average function.

    You need a tri-for loop to access all elements of the array (like you did in the main ).
    So now let's write again our average function

    Code:
    float gradeAve(int ***c)
    {
        float sum=0;
        int grade,student,class;//local variables
     
        for(student=0; student<NUMBER_OF_STUDENTS; student++)
        {//for loop for accessing 3 dimensional array
            
              for(class=0;class<NUMBER_OF_CLASSES;class++)
              {
         
                      for(grade=0; grade<NUMBER_OF_GRADES; grade++)
                     {
             
                               sum+=c[student][class][grade];
                      }
                }
          }
         
        return (sum/NUMBER_OF_GRADES);
    }
    Do you agree ?
    Code - functions and small libraries I use


    It’s 2014 and I still use printf() for debugging.


    "Programs must be written for people to read, and only incidentally for machines to execute. " —Harold Abelson

  4. #19
    Registered User
    Join Date
    Oct 2012
    Posts
    126
    Quote Originally Posted by std10093 View Post
    It crashed in the function of the average.

    In main, when you were filling the array you said
    Code:
    for(student=0; student<NUMBER_OF_STUDENTS; student++)
        {//for loop for populating 3 dimensional array
            for(class=0;class<NUMBER_OF_CLASSES;class++)
                {
         
            for(grade=0; grade<NUMBER_OF_GRADES; grade++)
                {
                if(grade==0){
                    printf("Enter in the grade for student %d in subject %d:\n", student+1, class+1);
                    scanf("%d", &array[student][class][grade]);
                }else
                    scanf("%d",&array[student][class][grade]);
    }
    }
    }
    So you went through every single cell of your array.

    Now in the average function you want to get the value of every single cell and add it to the sum.

    Here is your function
    Code:
    float gradeAve(int ***c)
    {
      float sum=0;
        int grade;//local variables
     
            for(grade=0; grade<NUMBER_OF_GRADES; grade++)
            {
                sum+=c[NUMBER_OF_STUDENTS][NUMBER_OF_CLASSES][NUMBER_OF_GRADES];//only takes sum of the grades and divides by number of grades
            }
         
        return (sum/NUMBER_OF_GRADES);
     
    }
    You have a 3D array and only one counter. This usually is wrong.

    Think simple. Let's say we have a single int array of 5 elements.
    Code:
    int N = 5;
    int array[N];
    and then you want to access an element and you say
    Code:
    printf("%d\n",array[N]);
    As you know matrices start counting from zero, thus the last element is in position N-1.
    So if you say array[N] you access memory that is not yours. <--ERROR

    This is pretty much what you do in the average function.

    You need a tri-for loop to access all elements of the array (like you did in the main ).
    So now let's write again our average function

    Code:
    float gradeAve(int ***c)
    {
        float sum=0;
        int grade,student,class;//local variables
     
        for(student=0; student<NUMBER_OF_STUDENTS; student++)
        {//for loop for accessing 3 dimensional array
            
              for(class=0;class<NUMBER_OF_CLASSES;class++)
              {
         
                      for(grade=0; grade<NUMBER_OF_GRADES; grade++)
                     {
             
                               sum+=c[student][class][grade];
                      }
                }
          }
         
        return (sum/NUMBER_OF_GRADES);
    }
    Do you agree ?
    Lol, wow is all I can say. I know better than this

  5. #20
    SAMARAS std10093's Avatar
    Join Date
    Jan 2011
    Location
    Nice, France
    Posts
    2,675
    Quote Originally Posted by Sorinx View Post
    Lol, wow is all I can say. I know better than this
    Which means? :P
    Code - functions and small libraries I use


    It’s 2014 and I still use printf() for debugging.


    "Programs must be written for people to read, and only incidentally for machines to execute. " —Harold Abelson

  6. #21
    SAMARAS std10093's Avatar
    Join Date
    Jan 2011
    Location
    Nice, France
    Posts
    2,675
    What I want to say, is that did you see what was the error? Did you fix it?

    Also do not forget that the free function is wrong
    Code - functions and small libraries I use


    It’s 2014 and I still use printf() for debugging.


    "Programs must be written for people to read, and only incidentally for machines to execute. " —Harold Abelson

  7. #22
    Registered User
    Join Date
    Oct 2012
    Posts
    126
    Nah just commenting on my own stupidity, but I'm literally falling asleep, looking at free function now. never did much with malloc prior

  8. #23
    Registered User
    Join Date
    Oct 2012
    Posts
    126
    Code:
    void freeArray(int ***a) {
          
    int i,j;
    for(i = 0; i <=NUMBER_OF_STUDETS; i++){
        for(j = 0; j <= NUMBER_OF_CLASSES; j++){
            free(a[i][j]);
        }
        free(a[i]);
    }
    free(a);
        
    }
    Last edited by Sorinx; 12-13-2012 at 06:42 AM.

  9. #24
    SAMARAS std10093's Avatar
    Join Date
    Jan 2011
    Location
    Nice, France
    Posts
    2,675
    That was a better try from the first-one posted. Again you are going out of boundaries because you start from zero in the for-loops but in the condition you have <= instead of < .

    Moreover you use NUMBER_OF_GRADES instead of NUMBER_OF_CLASSES.

    Here is what you should write
    Code:
    void freeArray(int ***a)
    {
            int i,j;
            for(i = 0; i < NUMBER_OF_STUDENTS; i++){
                    for(j = 0; j < NUMBER_OF_CLASSES; j++){
                            free(a[i][j]);
                    }
                    free(a[i]);
            }
            free(a);
    }
    Every time you malloc memory never forget to free it!

    Every time you malloc memory take a piece of paper and draw what you are allocating
    Salem likes this.
    Code - functions and small libraries I use


    It’s 2014 and I still use printf() for debugging.


    "Programs must be written for people to read, and only incidentally for machines to execute. " —Harold Abelson

  10. #25
    SAMARAS std10093's Avatar
    Join Date
    Jan 2011
    Location
    Nice, France
    Posts
    2,675

    Allocate dynamically 2D array

    Pretty often I see questions about dynamic memory allocation on arrays. So I decided to write a small program that creates, fills, prints and frees a 2D array and a 3D array. In this post you will find the code for the 2D.

    I something is not clear to you, just take a piece of paper and draw the memory

    Allocate 2D array dynamically :
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int **get(const int N, const int M);
    void fillArray(int** array, const int N, const int M);
    void printArray(int** array, const int N, const int M);
    void _free(int **array, const int N);
    
    int main(void)
    {
    	int **array;
    	int n = 2;
    	int m = 3;
    
    	array = get(n, m);
    			
    	fillArray(array, n, m);
    
    	printArray(array, n, m);
    
    	_free(array, n);
    
    	return 0;
    }
    
    int **get(const int N, const int M) /* Malloc the array */
    {
    	int i,**array;
    	array=malloc(N*sizeof(int *));
        	if ( array == NULL )
        	{
    		printf("Can not allocate memory. Exiting ...\n");
            	exit (0);
        	}
        	for(i=0 ; i<N ; i++)
        	{
            	array[i]=malloc( M*sizeof(int) );
            	if ( array[i] == NULL )
    		{
    			printf("Can not allocate memory. Exiting ...\n");
            		exit (0);
    		}
        	}
        	return array;
    }
    
    void fillArray(int** array, const int N, const int M)
    {
    	int i, j;
    	for( i = 0 ; i < N ; i++ )
            {
                    for( j = 0 ; j < M ; j++ )
                    {	
    			array[i][j] = j;
    		}
    	}
    }
    
    void printArray(int** array, const int N, const int M)
    {
    	int i, j;
            for( i = 0 ; i < N ; i++ )
            {
                    for( j = 0 ; j < M ; j++ )
                    {
                            printf("array[%d][%d] = %d\n",i, j, array[i][j]);
                    }
    		printf("\n");
            }
    }
    void _free(int **array, const int N)
    {
    	int i;
    	for(i=0 ; i<N ; i++)
        	{
            	free(array[i]);
        	}
        	free(array);
    }
    Code - functions and small libraries I use


    It’s 2014 and I still use printf() for debugging.


    "Programs must be written for people to read, and only incidentally for machines to execute. " —Harold Abelson

  11. #26
    SAMARAS std10093's Avatar
    Join Date
    Jan 2011
    Location
    Nice, France
    Posts
    2,675

    Allocate dynamically 3D array

    The 3D array :
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int ***get(const int N, const int M, const int K);
    void fillArray(int*** array, const int N, const int M, const int K);
    void printArray(int*** array, const int N, const int M, const int K);
    void _free(int ***array, const int N, const int M);
    
    int main(void)
    {
            int ***array;
    	int n = 2;
    	int m = 3;
    	int k = 2;
    
            array = get(n, m, k);
    
            fillArray(array, n, m, k);
    
            printArray(array, n, m, k);
    
            _free(array, n, m);
    
            return 0;
    }
    
    int ***get(const int N, const int M, const int K) /* Malloc the array */
    {
            int i, j,***array;
            array=malloc(N*sizeof(int **));
            if ( array == NULL )
            {
                    printf("Can not allocate memory. Exiting ...\n");
                    exit (0);
            }
            for(i=0 ; i<N ; i++)
            {
                    array[i]=malloc( M*sizeof(int*) );
                    if ( array[i] == NULL )
                    {
                            printf("Can not allocate memory. Exiting ...\n");
                            exit (0);
                    }
    		for( j = 0 ; j < M ; j++ )
    		{
    			array[i][j] = malloc( K*sizeof(int) );
    			if ( array[i][j] == NULL )
                    	{
                            	printf("Can not allocate memory. Exiting ...\n");
                            	exit (0);
                    	}
    		}
            }
            return array;
    }
    
    void fillArray(int*** array, const int N, const int M, const int K)
    {
            int i, j, k;
            for( i = 0 ; i < N ; i++ )
            {
                    for( j = 0 ; j < M ; j++ )
                    {
    			for( k = 0 ; k < K ; k++ )
                    	{
                            	array[i][j][k] = k;
    			}
                    }
            }
    }
    
    void printArray(int*** array, const int N, const int M, const int K)
    {
            int i, j, k;
            for( i = 0 ; i < N ; i++ )
            {
                    for( j = 0 ; j < M ; j++ )
                    {
                            for( k = 0 ; k < K ; k++ )
                            {
                            	printf("array[%d][%d][%d] = %d\n", i, j, k, array[i][j][k]);
                            }
                    }
    		printf("\n");
            }
    }
    
    void _free(int ***array, const int N, const int M)
    {
            int i, j;
            for(i = 0 ; i < N ; i++)
            {
    		for(j = 0 ; j < M ; j++)
            	{
    			free(array[i][j]);
    		}
                    free(array[i]);
            }
            free(array);
    }
    Hope that this code will help people
    Code - functions and small libraries I use


    It’s 2014 and I still use printf() for debugging.


    "Programs must be written for people to read, and only incidentally for machines to execute. " —Harold Abelson

Page 2 of 2 FirstFirst 12
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 17
    Last Post: 07-06-2011, 11:44 AM
  2. Replies: 3
    Last Post: 12-10-2010, 07:51 AM
  3. Dynamic Array of Object Fucntion call.
    By Spitball04 in forum C++ Programming
    Replies: 5
    Last Post: 09-15-2004, 10:40 AM
  4. dynamic memory allocating error
    By valhall in forum C Programming
    Replies: 2
    Last Post: 04-04-2003, 09:49 AM
  5. Allocating dynamic memory for structs
    By Nevyn in forum C Programming
    Replies: 4
    Last Post: 09-17-2001, 11:54 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21