-
Can anyone explain why this happen each time i run my prog?
Code:
#include<stdio.h>
#include<stdlib.h>
int **B;
int pinfun(int i,int x,int y ,int n,int **B);
int main (void){
int m,j,k;
scanf("%d",&m);
B=malloc((m+200) * sizeof(int *));
for(j=0;j<m;j++){
B[j]=malloc(m*sizeof(int));
}
for(j=0;j<m;j++){
for(k=0;k<m;k++){
*(*(B+j)+k)=0;
}
}
pinfun(1,0,0,m,B);
for(j=0;j<m;j++){
for(k=0;k<m;k++){
printf("%d ",B[j][k]);
}
printf("\n\n");
}
getchar();
getchar();
}
int pinfun(int i,int x,int y,int n,int **B){
if(i<=n*n){
if((pinfun(i+1,x+3,y,n,B)==1)&&(y>=0)&&(y<=n)&&(x>=0)&&(x<=n)&&((B[x][y])==0)){
B[x][y]=i;
return 1;
}
if((pinfun(i+1,x-3,y,n,B)==1)&&(y>=0)&&(y<=n)&&(x<=n)&&(x>=0)&&(B[x][y]==0)){
B[x][y]=i;
return 1;
}
if((pinfun(i+1,x,y+3,n,B)==1)&&(y>=0)&&(y<=n)&&(x<=n)&&(x>=0)&&(B[x][y]==0)){
B[x][y]=i;printf("%d\n",i);
return 1;
}
if((pinfun(i+1,x,y-3,n,B)==1)&&(y>=0)&&(y<=n)&&(x<=n)&&(x>=0)&&(B[x][y]==0)){
B[x][y]=i;
return 1;
}
if((pinfun(i+1,x-2,y-2,n,B)==1)&&(y>=0)&&(y<=n)&&(x<=n)&&(x>=0)&&(B[x][y]==0)){
B[x][y]=i;
return 1;
}
if((pinfun(i+1,x+2,y+2,n,B)==1)&&(y>=0)&&(y<=n)&&(x<=n)&&(x>=0)&&(B[x][y]==0)){
B[x][y]=i;
return 1;
}
if((pinfun(i+1,x+2,y-2,n,B)==1)&&(y>=0)&&(y<=n)&&(x<=n)&&(x>=0)&&(B[x][y]==0)){
B[x][y]=i;
return 1;
}
if((pinfun(i+1,x-2,y+2,n,B)==1)&&(y>=0)&&(y<=n)&&(x<=n)&&(x>=0)&&(B[x][y]==0)){
B[x][y]=i;
return 1;
}
if((y<0)||(y>n)||(x>n)||(x<0)||B[x][y]!=0){
return 0;
}
}
else{
B[x][y]=i;
return 1;
}
}
For example if given number is 5
i expect an output like this
1 19 16 4 20
14 24 8 11 23
17 5 21 18 6
2 10 15 3 9
13 25 7 12 22
And my output is:
1 0 0 0 0
0 0 0 0 0
0 0 0 0 0
2 0 0 0 0
0 0 0 0 0
The overal problem is to fill a square with numbers such as it's size
1 placed allways in the first position
2 can be placed two boxes vertically or horizontaly or one box across from 1
So each number should be placed two boxes vertically or horizontaly or one box across from the last.
-
Split from http://cboard.cprogramming.com/showthread.php?t=87398
Please don't hijack threads with your own questions.
-
pinfun() keeps calling itself until i > n*n, incrementing x by three each time. By the time i is larger than n*n, x is larger than the number your user entered. That becomes a factor the first time you hit this:
Code:
else {
B[x][y]=i;
return 1;
}
B[x] is 0x00000000. When you try to dereference that address, you get a segmentation fault. For what it's worth, in your example of the user entering "5", the value of x is 72 when you attempt to use B (or, B[72] when you only allocated B[0] through B[4]).
I could probably be more help if I had a better idea of what you were trying to accomplish.
-
Ok Salem
I will be more carefull in the future.
Thanks