Thread: malloc problem

  1. #1
    Registered User
    Join Date
    Jan 2010
    Location
    on some of the worst place on earth
    Posts
    105

    malloc problem

    Hello everyone,I am now stucked to a program now which is just about adding two tables like matrices.This program must be a simple one for you but its a complicated one for me.I think everything in this program is fine except for the implementation of malloc function. each time i compile it shows an error in the malloc function line.Please look into it if all my declaration of the 2D arrays are correct.The program code is:

    Code:
    #include<stdio.h>
    #include<conio.h>
    #include<stdlib.h>
    #define COL 20
    void readinput(int (*x)[COL],int,int);//function prototypes
    void computesum(int (*x)[COL],int (*y)[COL],int (*z)[COL],int,int);
    void printout(int (*x)[COL],int,int);
    int main()
    {
    	int row,nor,noc;//nor=no of rows noc=no of columns
    	int (*a)[COL],(*b)[COL],(*c)[COL];//THIS STATEMENT DECLARES THAT a,b,c are pointers to dimensional arrays
    	printf("\nHOW MANY ROWS?  ");
    	scanf("%d",&nor);
    	printf("\nHOW MANY COLUMNS?  ");
    	scanf("%d",&noc);
    	for(row=0;row<nor;row++)
    	{
    		(*a)[row]=(int *) malloc (noc * sizeof(int));//dynamic memory allocation for arrays a,b,c
    		(*b)[row]=(int *) malloc (noc * sizeof(int));
    		(*c)[row]=(int *) malloc (noc * sizeof(int));
    	}
    	printf("\nREAD INPUT OF FIRST TABLE:\n");
    	readinput(a,nor,noc);//inputting first table(function call)
    	printf("\nREAD INPUT OF SECOND TABLE:");
    	readinput(b,nor,noc);//inputting second table(function call)
    	computesum(a,b,c,nor,noc);//computing the sum of the tables(function call)
    	printf("\nPRINTING OUTPUT\n");
    	printout(c,nor,noc);//showing the result(function call)
    	getch();
    	return 0;
    }
    void readinput(int (*x)[COL],int r,int c)
    {
    	int i,j;
    	for(i=0;i<r;i++)
    	{
    		for(j=0;j<c;j++)
    		{
    			scanf("%d",*(x+i)+j);//reading each element of the table
    		}
    	}
    	return;
    }
    void computesum(int (*x)[COL],int (*y)[COL],int (*z)[COL],int r,int c)
    {
    	int i,j;
    	for(i=0;i<r;i++)
    	{
    		for(j=0;j<c;j++)
    		{
    			*(*(z+i)+j) = *(*(x+i)+j) + *(*(y+i)+j);//adding corresponding elements
    		}
    	}
    }
    void printout(int (*x)[COL],int r,int c)
    {
    	int i,j;
    	for(i=0;i<r;i++)
    	{
    		for(j=0;j<c;j++)
    		{
    			printf("%-5d",*(*(x+i)+j));//printing out the numbers
    			if(j==c-1)
    			printf("\n");
    		}
    	}
    }
    Please post reply if you can.......thanks

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Code:
    int (*a)[COL],(*b)[COL],(*c)[COL];//THIS STATEMENT DECLARES THAT a,b,c are pointers to dimensional arrays
    Your comment is wrong. That statement declares that they are pointers to an array of integers that is COL elements in size. That is to say, it points to a 1D array of COL integers.

    Easy dynamic "2D arrays":
    Code:
    int **twodee;
    size_t rows, cols, x;
    
    ... fill out rows and cols some place ...
    
    twodee = malloc( rows * sizeof *twodee ); /* allocate rows number of pointers to integers */
    if( twodee )
    {
        for( x = 0; x < rows; x++ )
            twodee[ x ] = malloc( cols * sizeof **twodee ); /* allocate a row, cols elements in size */
    }
    Freeing works the same way. Free the rows first, then free the whole thing.
    Code:
    for( x = 0; x < rows; x++ )
        free( twodee[ x ] );
    free( twodee );

    Quzah.
    Hope is the first step on the road to disappointment.

  3. #3
    Registered User
    Join Date
    Jan 2010
    Location
    on some of the worst place on earth
    Posts
    105
    Easy dynamic "2D arrays":
    Code:
    int **twodee;
    size_t rows, cols, x;
    
    ... fill out rows and cols some place ...
    
    twodee = malloc( rows * sizeof *twodee ); /* allocate rows number of pointers to integers */
    if( twodee )
    {
        for( x = 0; x < rows; x++ )
            twodee[ x ] = malloc( cols * sizeof **twodee ); /* allocate a row, cols elements in size */
    }
    Freeing works the same way. Free the rows first, then free the whole thing.
    Code:
    for( x = 0; x < rows; x++ )
        free( twodee[ x ] );
    free( twodee );

    Quzah.[/QUOTE]
    Thanks quzah, for your reply and pointing out the correct statement.
    quzah, actually i am new to C programming, and dont want to go to more complex programming now or any alternative way.But i want to know what was wrong with my codes in the malloc allocation.I want to first clear out my concept in that way first.Please execute and run the codes to see the error.I have been trying a lot and stuck to this..................Please help me out..............Yours every timely help is appreciated

  4. #4
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    You are doing something in a very unusual way, due I think to our discussion the other day of pointers to arrays.

    But you don't want pointers to arrays here, you want arrays of pointers:

    Code:
    	int *a[nor], *b[nor], *c[nor], i;
    	for (i=0; i<nor; i++) {
    		a[i] = malloc(noc*sizeof(int));
    		b[i] = malloc(noc*sizeof(int));
    		c[i] = malloc(noc*sizeof(int));
    	}
    Notice you do not have to (cast)malloc in C.

    If you do not want to declare the size of the array initially you can use a pointer to a pointer (slightly counter-intuitive, but there you go):
    Code:
    	int **a, i;
    	a = malloc(nor*sizeof(int*));
    	for (i=0;i<nor;i++) a[i] = malloc(noc*sizeof(int));
    Notice "a" is malloc'd an array of pointers, not an array of ints, then each pointer is malloc'd it's row.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  5. #5
    Registered User
    Join Date
    Jan 2010
    Location
    on some of the worst place on earth
    Posts
    105

    mk27

    hi mk27,you are doing a great job always and always ready to help.Thanks....

    Anyway, in this problem i want pointer to arrays only.Here the expression
    int (*a)[COL],(*b)[COL],(*c)[COL];
    is declaring a,b,c as pointer to 2 dimensional arrays with their 2nd dimension as COL=20.

    actually i have been totally confused with pointers and multidimensional arrays.
    As it is given in book, to use a two dimensional array as pointer we should declare as

    data_type (*p)[2nd Dimension];//p being a pointer to 2D array

    which is equivalent to

    data_type x[1st dimension][2nd dimension];//x being a 2D array

    So i was trying to implement it in the program i had shown before.Now i am confused whether this pointer declaration of 2D arrays as shown is declaring a pointer to an array with a fixed space of 20 memory locations or is the memory space variable and later can be changed to more than 20, since we are using malloc to allocate memory space after it.
    Please reply.......

  6. #6
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by rakeshkool27 View Post
    Anyway, in this problem i want pointer to arrays only.
    You can want to use whatever you like -- cheese donuts from outer space, etc -- that does not mean it will work.

    AFAIK you have two choices: you can do it the way I demonstrated in post #4, or the way quzah demonstrated in post #2.

    Let me try and explain better why
    Quote Originally Posted by mk27
    you don't want pointers to arrays here, you want arrays of pointers
    int (*a)[5] is a pointer to an array of 5 ints. That means (*a)[0], (*a)[1], etc. are ints. Not pointers. So you cannot go:
    Code:
    (*a)[row]=(int *) malloc (noc * sizeof(int));
    So three more times:
    you don't want pointers to arrays here, you want arrays of pointers
    you don't want pointers to arrays here, you want arrays of pointers
    you don't want pointers to arrays here, you want arrays of pointers


    data_type (*p)[2nd Dimension];//p being a pointer to 2D array

    which is equivalent to

    data_type x[1st dimension][2nd dimension];//x being a 2D array
    This is NOT TRUE. I suggest you not worry about (*a)[x] for now.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  7. #7
    Registered User
    Join Date
    Jan 2010
    Location
    on some of the worst place on earth
    Posts
    105

    Mk27

    yep MK27,whatever you told is true.here we require arrays of pointers not pointers to arrays.So I am finding more about pointers in the book and trying to solve the problem..............Thanks

  8. #8
    Registered User
    Join Date
    Jan 2010
    Location
    on some of the worst place on earth
    Posts
    105
    MK27, finally it was solved using arrays of pointers.So i understood to represent 2D arrays we can use arrays of pointers.I actually thought it was applicable to strings only not number arrays.I got it now.
    but you said that we dont have to (cast) malloc in C, but without casting it shows compile error,so what is it then????

  9. #9
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by rakeshkool27 View Post
    MK27, finally it was solved using arrays of pointers.So i understood to represent 2D arrays we can use arrays of pointers.I actually thought it was applicable to strings only not number arrays.I got it now.
    but you said that we dont have to (cast) malloc in C, but without casting it shows compile error,so what is it then????
    You mean you get an error for not including the red bit?
    Code:
    x = (int*)malloc(500);
    Then you are using your compiler in C++ mode. It is an error in C++, but not in C.

    A void pointer (the return value of malloc) can be any other kind of pointer in C, so you never have to cast them. It is not an error to do so, just it is not necessary.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  10. #10
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    > is declaring a,b,c as pointer to 2 dimensional arrays with their 2nd dimension as COL=20.
    In which case, the single malloc to initialise each one of them reads
    Code:
    a = malloc ( nor * sizeof *a );
    // this gets you a[nor][20]; in effect
    The value of noc doesn't matter to the declaration of your pointers. You only need check that it is <= 20 for everything to work as expected.

    If you really want a variable number of columns, then you need to start with
    int **a;
    and the appropriate 2-step malloc sequence written out several times above.
    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.

  11. #11
    Registered User
    Join Date
    Jan 2010
    Location
    on some of the worst place on earth
    Posts
    105
    Quote Originally Posted by Salem View Post
    > is declaring a,b,c as pointer to 2 dimensional arrays with their 2nd dimension as COL=20.
    In which case, the single malloc to initialise each one of them reads
    Code:
    a = malloc ( nor * sizeof *a );
    // this gets you a[nor][20]; in effect
    The value of noc doesn't matter to the declaration of your pointers. You only need check that it is <= 20 for everything to work as expected.

    If you really want a variable number of columns, then you need to start with
    int **a;
    and the appropriate 2-step malloc sequence written out several times above.
    Yes salem,,,,i understood a bit of it.
    Since i am a beginner in pointer i am really stucked up and confused with these array and pointer stuffs.Do every beginner face problem initially with pointer or is it bcoz i have little concept? I dont know how will I master C......there is a long way to go........i dont even have the pointer concept clearly

  12. #12
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    A lot of beginners are confused by pointers. The best thing to do is study and experiment with them, which is what you are doing.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  13. #13
    Registered User
    Join Date
    Jan 2010
    Location
    on some of the worst place on earth
    Posts
    105

    About compilers

    Anyway MK27,which compiler do you use and which one is the best to use?
    I only write,compile and execute the programs and dont know anything much about the compilers.Is there anything like updating the library function or like that.
    I have downloaded some of the game programming codes which i have been not able to compile due to some errors.is this the problem with the compiler or the missing library functions?Can you advice.............If anyone knows please let me know.................

  14. #14
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    It could be a lot of things not least of which is the code itself. Not every example or demo someone has placed on the web is guaranteed to be free from errors.

    I use gcc, but I don't program on windows.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Memory problem with Borland C 3.1
    By AZ1699 in forum C Programming
    Replies: 16
    Last Post: 11-16-2007, 11:22 AM
  2. Replies: 12
    Last Post: 06-24-2005, 04:27 PM
  3. malloc and realloc
    By odysseus.lost in forum C Programming
    Replies: 3
    Last Post: 05-27-2005, 08:44 AM
  4. freeing problem with concurrent processes
    By alavardi in forum C Programming
    Replies: 2
    Last Post: 03-07-2005, 01:09 PM
  5. half ADT (nested struct) problem...
    By CyC|OpS in forum C Programming
    Replies: 1
    Last Post: 10-26-2002, 08:37 AM