user2688772
user2688772

Reputation: 347

Using malloc and calloc to create a step structure

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


int  main(int argc,char *argv[])
{
int i = 0;
int n;
int **matrix;

printf("%s","enter the value of n ie number of levels:" );
scanf("%d",&n);
matrix =(int **)malloc(n*sizeof(int *));

while(i<n)
{
matrix[i]= (int*)calloc((i+1),sizeof(int));
i++;
}


for (int i = 0; i < n; ++i)
{   
    for (int j = 0; j <n; ++j)
    {
        if (matrix[i][j]==0)
        {
        printf("%d  ",matrix[i][j] );
        }
        else
        {
            printf("%c ",'B' );
        }

    }
    printf("\n");
}


//printf("%p\n",(matrix[1]));




free(matrix);



return EXIT_SUCCESS;
}

I am trying to create a stair step like structure in using dynamic memory allocation.I purposely used calloc(seeing how zeroes look) so i can check if the array structure I want to create looks like what I want but for various inputs of n i only seem to get a normal 2d array only not like what i have described.Thanks for your help.

Upvotes: 0

Views: 124

Answers (2)

Dipto
Dipto

Reputation: 2738

You have allocated memory for a stair like pattern successfully, but while traversing, you are not following that.

Instead of

for (int i = 0; i < n; ++i)
{   
    for (int j = 0; j <n; ++j)
    {
    ...

you have to do

for (int i = 0; i < n; ++i)
{   
    for (int j = 0; j <i+1; ++j)
    {

If you go beyond i+1 in the inner loop, you may get a segmentation fault as you have not allocated memory for that.

Upvotes: 0

NPE
NPE

Reputation: 500853

Your code that allocates the structure is fine and does exactly what you want.

The code that looks for zeros is not fine. Since it reads past the allocated memory it results in undefined behaviour.

In other words, you cannot check whether a particular address has been calloc()ed by reading it and comparing the result to zero.

Once you fix the undefined behaviour, you'll be left with a memory leak: you need to free() each element of matrix before free()ing matrix itself.

Upvotes: 2

Related Questions