Randiir
Randiir

Reputation: 33

How can I print the following 2D array?

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

int ** letters (int*arr, int nr_elem)
{
    char **mat=(char**)malloc( nr_elem * sizeof(char*));

    int max =0;
    for (int i =0; i<nr_elem;i++)
    {
        if( *(arr + i) > max)
            max = *(arr + i);
    }

    for (int i=0; i<nr_elem; i++)
    {
        *mat=(char*)malloc((*(arr+i))*sizeof(char));
    }

    for(int i=0; i<nr_elem;i++)
      {

      for(int j=0; j<(*(arr+i)); j++)
        {

            mat[i][j] = 'a'+ (*(arr+i))-1;
            printf("mat[%d][%d] = %c\n", i, j, mat[i][j]);
        }
      }


}

int main()
{

    int a[] = {3, 4, 5, 2, 3};
    int n = 5;
    letters(a, n);
    return 0;
}

My final goal is to make the function print a matrix with 5 rows on which it will print the corresponding letter from array a, that same amount of times. For example line 1, will have letter 'c' printed 3 times, line 2 will have 'd' printed 4 times etc. For now I just want to print the matrix (i know the rest is not completely implemented, but I want to see what i have so far). it will show me that :

m[0][0] = 'c'
m[0][1] = 'c'
m[0][2] = 'c'
m[1][0] = 'd'
m[1][1] = 'd'
m[1][2] = 'd'
m[1][3] = 'd'

but then it cracks. Why?

Upvotes: 1

Views: 43

Answers (1)

Adrian Mole
Adrian Mole

Reputation: 51825

You have an error in the second for loop inside your letters function, where you should be allocating a char* pointer to each element of mat:

for (int i=0; i<nr_elem; i++)
{
//    *mat=(char*)malloc((*(arr+i))*sizeof(char)); // *mat keeps getting overwritten!
    mat[i] = malloc((*(arr+i))*sizeof(char)); // Allocates new block for each loop
}

In your code, your only ever assign the return from malloc to the first element of the mat array - each loop just overwrites the previously assigned value (i.e. *mat is the same as mat[0]).

Also, please see this post on (not) casting the return value of malloc: Do I cast the result of malloc?

Upvotes: 1

Related Questions