Search code examples
cmultidimensional-arraydynamic-allocation

dynamically allocated 2D array Runtime error


I was trying to solve this problem but this message appeared after finishing the first test case loop, and when i uploaded it to codeforces it gets a Run time error verdict!

Given 2D Array of integers of size N*N. Print the sum of the perfect square numbers.

For example, 25, 16, 36 and 9 are perfect square numbers. But 35, 17, 23 and 11 are not.

Input
Your input consists of T (1 ≤ T ≤ 10^2) test cases. Each test case contains only 1 integers N (1 ≤ N ≤ 10^2). N lines follow each line contains N space separated integers (1 ≤ Nij ≤ 10^2).

Output
For each test case print a single integer in a single line, the required sum.

Example input

2
2
9 97
8 56
3
1 18 6
16 42 100
25 16 17

output:

9
158

Code:

void main()
{
int n, x, **z, m, i, j, q, p, sum;
float y;

scanf("%d", &x);
for (i = 0; i < x; i++)
{
    sum = 0;
    scanf("%d", &n);
    z = (int**)malloc(sizeof(int*)*n);
    for (j = 0; j < n; j++)
        z[j] = (int*)malloc(sizeof(int)*n);
    for (p = 0; p < n; p++)
        for (q = 0; q < n; q++)
        {
            scanf("%d", &z[p][q]);
            m = sqrt(z[p][q]);
            y = sqrt(z[p][q]) - m;
            if ((y) == 0)
                sum += z[p][q];
        }
    printf("%d\n", sum);
    for (j = 0; j < n; j++)
        free(z[i]);
    free(z);
}
return;}

image of message i get when i debug on VSc++

Update: free(z[i]) was edited to be free(z[j])

Update: thanks for jpw it worked well in VS, but this time resulted in compilation error in Codeforces rather than Runtime error.


Solution

  • It seems to be a simple typo...

    free(z[i]); at the end should be free(z[j]);

    Changing that makes it run fine in ideone