Here is an example of my code (magic square):
int magicsqr(int *magic,int size);
int main()
{
int size,*ptr;
char stop;
repeat:
printf("Please Enter an Odd number for the magic square(3 or greater):\n");
scanf("%d",&size);
fflush(stdin);
ptr=(int*)calloc(size*size,sizeof(int));
while((size%2==0)||(size<=1))
{
printf("U entered a wrong number.\n");
repeat1:
printf("Do you wish to continue?(Y or N)\n");
scanf("%c",&stop);
fflush(stdin);
if(stop=='Y'||stop=='y')
goto repeat;
else if(stop=='N'||stop=='n')
printf("Thanks for trying our beta program.\n");
else
{
printf("U entered a wrong character.\n");
goto repeat1;
}
}
magicsqr(ptr,size);
return 0;
}
int magicsqr(int *magic,int size)
{
int i,j,num;
i=1;
j=(size+1)/2;
for(num=1;num<=size*size;num++)
{
*(magic+i*size+j)=num;
if(num%size==0){
i++;
continue;
}
if(i==1)
i=size;
else
i--;
if(j==size)
j=1;
else
j++;
}
for(i=1;i<=size;i++)
{
printf("\n");
for(j=1;j<=size;j++)
printf("%d\t",*(magic+i*size+j));
}
}
so i got few questions that confused me ..
1- As far as i know Arr[i][j]==*(Arr[i]+j)
so why only this works : *(magic+i*size+j)
.
2- I read a lot in passing 2 dimensional array into a function using pointers but somehow i am still confused, how to represent a 2D array or more in this code.
3- I am still a beginner in programming, so i wish if you could explain a little.
- Thanks a lot guys, finally i got it worked using pointer to pointer and array of pointers.