0

Please if someone tell me what is wrong with this code by using malloc function, I dont know what to do.

 #include <stdio.h>
 #include <string.h>
 #include <stdlib.h>
 #include <process.h>

 int main()
 {
 int row;
 int column;
 int j=0;
 int **ptr;

 printf("Number of rows: \n");
 scanf ("%d",&row);
 printf("Number of columns: \n"); 
 scanf ("%d",&column);  

There is a mistake, ???? please if someone know what to do to write

 int* ptr = malloc( row * sizeof(*ptr) ); /*Allocate integer pointers for the rows */
    if(ptr != NULL)
    {
        for(int m = 0; m < row; m++) /* Loop through each row pointer to allocate     memory for columns*/
        {
            /* Set p[i] pointer to a block of memory for 'column' number of integers */
            ptr[m] = malloc(column * sizeof **ptr); /*Here, sizeof(**p) is same as sizeof(int) */
            if(ptr[m] == NULL)
            {
                printf("Memory allocation failed. Exiting....");
                 exit(1);  
            }
        }

    }
    else
    {
        printf("Memory allocation failed. Exiting....");
         exit(1);  
    }





for(int i=0; i<row; i++)
{
   for(int j=0; j<column; j++)
{
printf("Enter values [%d] [%d]: \n",i+1,j+1 );  
scanf ("%d",&ptr[i][j]);
}
}


free (ptr); 
system("PAUSE");    
return 0;
}

Pleas for answer because i need this code in school till 3. Jan. 2014

  • 2
    Remove the `int *ptr` from your initial alloc. You're already declaring it as `int **ptr;` in the prior declaration. This: `int* ptr = malloc( row * sizeof(*ptr) );` should be this: `ptr = malloc( row * sizeof(*ptr) );` – WhozCraig Dec 27 '13 at 20:43

5 Answers5

3

Change this line…

int* ptr = malloc( row * sizeof(*ptr) );

… to this…

ptr = malloc( row * sizeof(*ptr) );

You've already declared ptr here:

int **ptr;
Fiddling Bits
  • 8,712
  • 3
  • 28
  • 46
1

If you feel the need to use malloc (and free) for dynamic allocation, then there are some good answers already here. But please consider that you do not need to use malloc at all in your example.

You can simply declare an automatic array of variable size as shown below. Your code will be very clear and the potential for bugs will be reduced. This feature is available in the C language since ISO C99 (earlier, in some compliers).

There can be an argument to not use variable sized array declaration if the array will be extremely large. Your example is taking user input for each array element, so that tells me you're not allocating hundreds of megabytes or anything that would blow up the stack! So this will work for you just fine. Good luck.

#include <stdio.h>

int main()
{
    int rows;
    int columns;

    printf("Number rows: ");
    scanf ("%d", &rows);
    printf("Stevilo columns: "); 
    scanf ("%d", &columns);  

    int values[rows][columns];   /* <-- no need to malloc(), no need to free() */

    for(int i=0; i<rows; i++) {
        for(int j=0; j<columns; j++) {
            printf("Enter value[%d][%d]: ",i+1,j+1 );  
            scanf("%d", &values[i][j]);
        }
    }
}
Darren Stone
  • 2,008
  • 13
  • 16
0

Instead of using sizeof (ptr) and sizeof **ptr, try to use sizeof(int*) in the first malloc, and sizeof(int) in the second malloc.

Talysson
  • 1,363
  • 1
  • 9
  • 13
0

thank you all for so fast answers, it was very helpful, now it works without any error!

I did so:

    int** ptr = (int**) malloc(row * sizeof(int)); /*Allocate integer pointers for the rows */
    if(ptr != NULL)
    {
        for(int m = 0; m < row; m++) /* Loop through each row pointer to allocate memory for columns*/
        {
            /* Set p[i] pointer to a block of memory for 'column' number of integers */
            ptr[m] = (int*)malloc(column * sizeof(int)); /*Here, sizeof(**p) is same as sizeof(int) */
            if(ptr[m] == NULL)
            {
                printf("Memory allocation failed. Exiting....");
                 exit(1);  
            }
        }

    }
    else
    {
        printf("Memory allocation failed. Exiting....");
         exit(1);  
    }
-2

First off your code is very messy. Your malloc call should also look like this for example:

   int** ptr = (int**)malloc(row * sizeof(ptr*));

The size of a pointer will always (almost all the time unless you are on a computer made in 1982) be 4 because its a memory address aka an int wich is 4 bytes. In your for loop it should read something like:

    ptr[m] = (int*)malloc(column * sizeof(ptr));
Katianie
  • 589
  • 1
  • 9
  • 38
  • Please, don't teach to cast the return from `malloc`, this is C and not C++. The original code had it right on that point, you now got it wrong. – Jens Gustedt Dec 27 '13 at 23:15
  • `sizeof(ptr*}` is incorrect syntax; it should be `sizeof *ptr`. And, in the assignment to `ptr[m]`, `sizeof(ptr)` is incorrect; it should be `sizeof *ptr[m]`. – Eric Postpischil Dec 28 '13 at 10:41
  • The size of a pointer is neither always four bytes nor always the size of an `int`. – Eric Postpischil Dec 28 '13 at 10:46
  • @JensGustedt If casting malloc is wrong then how come thats what i see for examples almost every example of malloc? What exactly is wrong with doing that? – Katianie Dec 30 '13 at 14:28
  • @Katianie, probably because you are looking at examples that are written for C++ and not for C. The top of the FAQ here on SO for C is the one that you are looking for: http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc – Jens Gustedt Dec 30 '13 at 14:52
  • @EricPostpischil sizeof is a function and thus I call it as a function. I don't see why you would want to write it in that style. Also for complexity sake i went with int is almost always 4 because its never been otherwise for me. – Katianie Dec 30 '13 at 15:48
  • @Katianie: `sizeof` is an operator, not a function (per C 2011 clause 6.5.3.4). However, the important part of my comment is not the parentheses but the syntax of the first operand and the correctness of the second. `ptr*` is not a valid expression or type name; `*ptr` is correct. And `sizeof(ptr)` for the second operand allocates memory for `ptr` objects, but the memory is intended to be used for objects pointed to be `ptr[m]`, hence `*ptr[m]`. Using `sizeof(ptr)` will allocate the wrong amount of space in implementations where an `int **` has a different size than an `int`. – Eric Postpischil Dec 30 '13 at 19:42
  • @Katianie: The fact that an `int` has never been other than four bytes to you is irrelevant to whether it always is. The statement that an `int` is always four bytes is false. – Eric Postpischil Dec 30 '13 at 19:43
  • @EricPostpischil Sorry for trying to make his life easier. – Katianie Dec 30 '13 at 19:44