0

i have this small piece of code which i cant get to work. I am kinda new and i just cant find a mistake i did. Thanks

int main (void)
{
    int **array;
    int i,j, m;

    scanf("%d", &m);

    array = malloc(sizeof(int) * (m*m));


    for (i = 0; i < m; i++) 
    {   
        for (j = 0; j < m; j++) 
        {       
            scanf("%d", &array[i][j]);                     
        }
    }   

        for (i = 0; i < m; i++) 
        {   
            for (j = 0; j < m; j++) 
            {       
                printf("%d", array[i][j]);                  
            }
        }   

    return 0;
}
2
  • What debugging have you done to narrow it down? Commented Nov 20, 2017 at 17:55
  • Check your input! You have m*m+1 scanf's, and not once do you check the result or the return value. Commented Nov 20, 2017 at 17:56

1 Answer 1

5

What you are allocating is an one dimensional array of size m*m but you are using it as if you have allocated a jagged array where each row contains m elements.

You can allocate a bit different way than what you did

array = malloc(sizeof *array * m);
if( array == NULL)
{
   // error in malloc
}
for(size_t i =0; i<m; i++)
{
   array[i]=  malloc(sizeof *array[i] * m);
   if( array[i] == NULL)
   {
      // error

   }
}
...
for(size_t i = 0; i<m ; i++)
   free(array[i]);
free(array);

Alternatively you can put all the elements in a linear manner using i and j.

int *array;
...
for (i = 0; i < m; i++) 
{   
    for (j = 0; j < m; j++) 
    {       
        if( scanf("%d", &array[i*m+j]) != 1){
           // error in getting input.
        }                     
    }
}   
...
free(array);

Same goes with printf also.

Also don't forget to free the memory you have allocated dynamically after you are done working with it.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.