简体   繁体   中英

2d array initialized with malloc/calloc

Alright, I'm having trouble understanding how to use malloc in calloc to initalize an array. I'm trying to do some practice by creating a 2 * 3 matrix that stores user-input values. The only part of the code that I don't want to change is using **matrix instead of matrix[5][7]. Any suggestions?

Here's my code so far (I keep getting segmentation faults):

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

main(){

    int i, j;

    int **mat = (int **)malloc(2 * 3 * sizeof(int*));

    for(i=0;i<2;i++)
      for(j=0;j<3;j++){

      printf("Input a value for Array[%d][%d]: ",i,j);

      scanf("%d",&mat[i][j]);

      }
    for(i=0;i<2;i++)
      for(j=0;j<3;j++)
        printf("%d\t",mat[i][j]);

}

EDIT: I appreciate the help everyone! My code now works without faults. Here's the what it looks like:

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

main(){

int i, j;

int **mat;

  mat = malloc(2 *sizeof(int *));

for(i=0;i<2;i++){

  mat[i] = malloc(3 *sizeof(int));

        for(j=0;j<3;j++){

        printf("Input a value for Array[%d][%d]: ",i,j);

        scanf("%d",&mat[i][j]);

        }
  }

for(i=0;i<2;i++)
  for(j=0;j<3;j++)
  printf("%d\t",mat[i][j]);

return 0;
}

If there's any reason I should make more edits, let me know.

mat is a double pointer. You need to allocate memory for array of pointers and then allocate memory to each pointers individually.

mat[0] = malloc(sizeof(int) *n ); /* n = Number of elements */

mat[0] should have some memory allocate before writing to it.

Then your scanf() where you have mat[i][j] makes sense. No need to cast malloc()

I hope my answer in any case will be useful for you.

If you are using a compiler that supports C99 then you can use at least the following two approaches.

In the first case you can allocate at once a two-dimensional array. In the second case ( that is the case described in your post) you can allocate two one-dimensional arrays that will simulate one two-dimensional array.

Below there is a program that demonstrates the both approaches.

Also do not forget to free allocated arrays. Take into account how the arrays are freed in each case.

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

int main( void )
{
    {
        size_t N = 2;
        size_t M = 3;

        int ( *mat )[M] = malloc( N * M * sizeof( int ) );

        for ( size_t i = 0; i < N; i++ )
        {
            for ( size_t j = 0; j < M; j++ )
            {
                printf( "Input a value for Array[%d][%d]: ", i, j );
                scanf( "%d", &mat[i][j] );
            }
        }

        printf( "\n" );

        for ( size_t i = 0; i < N; i++ )
        {
            for ( size_t j = 0; j < M; j++ )
            {
                printf( "%2d ", mat[i][j] );
            }

            printf( "\n" );
        }

        free( mat );
    }

    {
        size_t N = 2;
        size_t M = 3;

        int **mat = malloc( N * sizeof( int * ) );

        for ( size_t i = 0; i < N; i++ )
        {
            mat[i] = malloc( M * sizeof( M ) );
            for ( size_t j = 0; j < M; j++ )
            {
                printf( "Input a value for Array[%d][%d]: ", i, j );
                scanf( "%d", &mat[i][j] );
            }
        }

        printf( "\n" );

        for ( size_t i = 0; i < N; i++ )
        {
            for ( size_t j = 0; j < M; j++ )
            {
                printf( "%2d ", mat[i][j] );
            }

            printf( "\n" );
        }

        for ( size_t i = 0; i < N; i++ ) free( mat[i] );
        free( mat );
    }

    return 0;
}

In the both cases the program will output the same matrix

1  2  3 
4  5  6 

If to eneter these values.

You can test the program at www.ideone.com selecting language strict C99 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM