Reputation: 33
I am writing this simple code for dynamically allocated 2D array and displaying it. When I execute this program, it gives garbage value in the first row. How is that? Any errors in my program?
#include <stdio.h>
#include <stdlib.h>
int main()
{
int **ptr, limit, i, j;
printf("Enter the limit: ");
scanf("%d", &limit);
ptr = (int **) malloc(limit * (sizeof(int)));
for(i=0; i<limit; i++)
{
*(ptr+i) = (int *) malloc((i+1) * sizeof(int));
for(j=0; j<=i; j++)
{
ptr[i][j] = i;
}
}
for(i=0; i<limit; i++)
{
for(j=0; j<=i; j++)
{
printf("%d ", ptr[i][j]);
}
printf("\n");
}
return 0;
}
Output:
Enter the limit: 4
0
1 1
2 2 2
3 3 3 3
Enter the limit: 5
9478320
1 1
2 2 2
3 3 3 3
4 4 4 4 4
If I try to print the 2D array with the limit is less than or equal to 4, it works fine. What am I missing here..
Thanks
Upvotes: 1
Views: 256
Reputation: 35154
Maybe there are other issues as well; but one thing is for sure - you are allocating the wrong size for the pointer elements:
ptr = (int **) malloc(limit * (sizeof(int)));
though there should be limit
objects of pointers to int, you are allocating ints. So it needs to be...
ptr = malloc(limit * (sizeof(int*)));
BTW: In C, avoid casting the result of malloc
.
Upvotes: 6