- #1
Fb.Researcher
- 9
- 0
I am a beginer in C programming,so I have just became familiar with pointers.The problem I am writing a program to solve requires me to allocate a multidimensional array, reallocate it and use it in some functions.The simplest problem would be:allocating a two dimensional array, ask a function to print it's components, reallocate it and subtract it's rows by 2 and again give it to the function to print it's components.My code is:
main(){
int **a,i,j;
a=calloc(6,sizeof(int *));
for(i=0;i<6;i++)
a=calloc(6,sizeof(int));
for(i=0;i<6;i++)
for(j=0;j<6;j++)
a[j]=i*j;
write(a);
return (0);
}
write is the function that should print the components:
void write(int a[6][6])
{ int i,j;
for(i=0;i<6;i++)
{for(j=0;j<6;j++)
printf("%4i",**a[j]);
printf("\n");
}
}
Now here are my questions:
Why the array pointer should be **a and not *a?I have this syntax by searching through the internet but there was no other explanation about it.The only thing I could find in books was that a pointer is defined by a statement like :
int *a;
another problem is using the allocated array in a function.You see compiling the code gives me the following error(Itried to solve it by defining the right kind of argument but I think the failure is due to my lacking of knowledge in pointers.I know about the calling by reference and value)
c:24:2: warning: passing argument 1 of ‘write’ from incompatible pointer type [enabled by default]
note: expected ‘int (*)[6]’ but argument is of type ‘int **’
The program is not compiled.My compiler is gcc.Please help me!
main(){
int **a,i,j;
a=calloc(6,sizeof(int *));
for(i=0;i<6;i++)
a=calloc(6,sizeof(int));
for(i=0;i<6;i++)
for(j=0;j<6;j++)
a[j]=i*j;
write(a);
return (0);
}
write is the function that should print the components:
void write(int a[6][6])
{ int i,j;
for(i=0;i<6;i++)
{for(j=0;j<6;j++)
printf("%4i",**a[j]);
printf("\n");
}
}
Now here are my questions:
Why the array pointer should be **a and not *a?I have this syntax by searching through the internet but there was no other explanation about it.The only thing I could find in books was that a pointer is defined by a statement like :
int *a;
another problem is using the allocated array in a function.You see compiling the code gives me the following error(Itried to solve it by defining the right kind of argument but I think the failure is due to my lacking of knowledge in pointers.I know about the calling by reference and value)
c:24:2: warning: passing argument 1 of ‘write’ from incompatible pointer type [enabled by default]
note: expected ‘int (*)[6]’ but argument is of type ‘int **’
The program is not compiled.My compiler is gcc.Please help me!