-4
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
    int score,i,j;
    int *ptr, *ptr1;
    int over;
    printf("Enter the number of over");
    scanf("%d",&over);
    ptr=(int*)malloc(over*sizeof(int));
    // do the iteration, outer for loop, read row by row...
    for(i=0; i <= (over-1); i++)
        {
            printf("%d%d ", i, ptr[i]);
            // inner for loop, for every row, read column by column and print the bar...
            printf("Enter the number of run per over");
            scanf("%d",&score);
            ptr1=(int*)malloc(score*sizeof(int));
            for(j = 1; j<= ptr1[i]; j++)
            // print the 'bar', and repeat...
                printf("|");
            // go to new line for new row, and repeats...
            printf("\n");
        }
    return 0;
}
Peter Miehle
  • 5,984
  • 2
  • 38
  • 55
emmie
  • 1

3 Answers3

4

You are using

ptr1=(int*)malloc(score*sizeof(int));

inside your for loop. That causes memory leak. You should free the memory.

You also have

 printf("%d%d ", i, ptr[i]);

But ptr[i] has not been assigned any value, so it just gives garbage value. The same problem occurs in

for(j = 1; j<= ptr1[i]; j++)

So you need to assign some value to them before using them like this.

Arun A S
  • 6,421
  • 4
  • 29
  • 43
0
  • Casting the result of malloc doesn't make any sense, it is pointless and potentially bad practice.
  • printf("%d%d ", i, ptr[i]);. You print the value of an uninitialized memory cell. This is undefined behavior and might in theory cause the program to crash on some platforms. If you need the memory allocated to be initialized to zero, you should be using calloc() instead.
  • ptr1=(int*)malloc(score*sizeof(int)); for(j = 1; j<= ptr1[i]; j++) This code makes no sense whatsoever and will crash the program. You use ptr1 as if it was an initialied array of integers, while it is actually an uninitialized, single integer.
Community
  • 1
  • 1
Lundin
  • 195,001
  • 40
  • 254
  • 396
0
#include <stdio.h>
#include <stdlib.h>

int main(void){
    int **scores;
    int over, score;
    int i, j;

    printf("Enter the number of over : ");
    scanf("%d", &over);
    scores = (int**)malloc(over*sizeof(int*));

    for(i = 0; i < over; i++){
        printf("%d ", i + 1);
        printf("Enter the number of run per over : ");
        scanf("%d", &score);
        scores[i] = (int*)malloc((score+1) * sizeof(int));// +1 for number of columns
        scores[i][0] = score;
        for(j = 1; j <= score; j++){
            printf("%d Enter the score : ", j);
            scanf("%d", &scores[i][j]);
        }
    }
    for(i = 0; i < over; i++){
        for(j = 1; j <= scores[i][0]; j++){
            printf("|%d", scores[i][j]);
        }
        printf("|\n");
    }
    //deallocate
    for(i = 0; i < over; i++)
        free(scores[i]);
    free(scores);
    return 0;
}
BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70