Reputation: 75
I have a 2d pointer and i use it as a matrix. For every line full of even numbers i want to add another line that will have the sum of elements. for ex:
initial
1 1 1
12 14 16
3 3 3
final
1 1 1
12 14 16
3 5 7
3 3 3
i have the following code and i think i have a shifting error can somedoy give me some sugestions.
#include <stdio.h>
#include <stdlib.h>
int suma(int x) //sum function
{
int s = 0, r = 0;
while (x != 0)
{
r = x % 10;
s = s + r;
x = x / 10;
}
return x;
}
int main(void)
{
int i, j, n, m, p, q, ii, **a, par = 0,r;
printf("nr de rows\n");
scanf("%d", &m);
printf("columns\n");
scanf("%d", &n);
a = (int**)malloc(m*sizeof(int*));
for (i = 0; i < m; i++)
{
a[i] = (int*)malloc(n*sizeof(int));
}
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
printf("a[%d][%d]=", i + 1, j + 1);
scanf("%d", &a[i][j]);
}
}
printf("\n\n\nmatricea initiala\n"); //initial matrix
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
printf("%d\t", a[i][j]);
}
printf("\n");
}
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
if (a[i][j] % 2 == 0)
{
par++;
}
else
{
par = 0;
}
}
if (par == n)
{
m++;
a = (int**)realloc(a, m*sizeof(int*));
a[m] = (int*)malloc(n*sizeof(int));
for (p = m; p >i; p--)
{
for (q = 0; q < n; q++)
{
a[p][q] = a[p - 1][q];
}
}
par = 0;
for (r = 0; r < n; r++)
{
a[i + 1][r] = suma(a[i][r]);
}
i--;
}
par = 0;
}
printf("\nmat finala\n"); //final matrix
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
printf("%d\t", a[i][j]);
}
printf("\n");
}
}
Upvotes: 0
Views: 50
Reputation: 40145
fix point:
1.return x;
--> return s;
2.for (i = 0; i < m; i++)
--> for (i = m-1; i >= 0; --i)
: The process from the bottom to the top
3.at after realloc, a[m] = (int*)malloc(n*sizeof(int));
--> a[m-1] = (int*)malloc(n*sizeof(int));
: a[m] is out of bounds.
4.for (p = m; p >i; p--)
--> for (p = m-1; p >i+1; p--)
5.i--;
--> //i--;
: It is no longer needed.
Upvotes: 3