#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;
}
答案 0 :(得分:4)
您正在使用
ptr1=(int*)malloc(score*sizeof(int));
在你的for循环中。这会导致内存泄漏。你应该释放记忆。
你也有
printf("%d%d ", i, ptr[i]);
但是ptr[i]
没有分配任何值,所以它只给出了垃圾值。
for(j = 1; j<= ptr1[i]; j++)
所以你需要在使用它们之前为它们分配一些值。
答案 1 :(得分:0)
printf("%d%d ", i, ptr[i]);
。您打印未初始化的内存单元格的值。这是未定义的行为,理论上可能导致程序在某些平台上崩溃。如果需要将分配的内存初始化为零,则应使用calloc()代替。ptr1=(int*)malloc(score*sizeof(int)); for(j = 1; j<= ptr1[i]; j++)
此代码没有任何意义,会导致程序崩溃。你使用ptr1好像它是一个初始化的整数数组,而它实际上是一个未初始化的单个整数。答案 2 :(得分: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;
}