I am not able to use pointer to array in Linux .It always shows error
when I try to read from keyboard or print to screen.
main()
{
int i,j;
int (*a)[2];
a=(int *)calloc(2,sizeof(int));
If your compiler did not issue a diagnostic for this statement, you
need to correct your configuration parameters or get one that deals
with the C language. The right hand side of your statement has type
pointer to int (courtesy of the cast). The left hand side has type
pointer to array of two int (from the definition of a). There is no
implicit conversion between these types. This is a constraint
violation requiring a diagnostic.
While we recommend not casting the return from the allocation
functions, in this case your cast serves to indicate that you do not
understand the type of a.
If you remove the cast (and remember to include stdlib.h), the
statement should allocate space for one array of two int. If you had
really intended to allocate space for two arrays, you should follow
the recommended practice of
a = calloc(2, sizeof *a);
In this case, malloc may be more appropriate since you never use the
zero values that calloc stores in the allocated area.
for(i=0;i<2;i++)
for(j=0;j<2;j++)
scanf("%d",(*(a+i)+j));
Here is where you introduce undefined behavior. You should consider
yourself fortunate that the UB manifested itself in an immediately
obvious manner. This discussion group is full of queries from
confused people who were not so fortunate.
Variable a is a pointer to an object (in this case an array of two
int.)
The expression a+i involves pointer arithmetic. (Pointer
arithmetic is different than "normal" arithmetic because the size of
the object pointed to participates. If p is a pointer to an object of
size 5, then p+i evaluates to an address that is 5*i bytes greater
than the value in p.) The expression evaluates to the address of the
i-th object after the one pointed to. Note that expression a+0, or
the equivalent a, evaluates to the address of the object pointed to,
which is exactly what we mean when we say a is a pointer to an object.
*a and the equivalent *(a+0) evaluate to the object, in this case
an array of two int.
*(a+i) evaluates to the i-th object after the one pointed to by a.
Unfortunately, in this case there is no such object whenever i is
greater that 0. You only allocated space for one array.
}
This shows segmentation fault?Why is this happening
But array of pointers works.
An array of pointers can work. A pointer to an array can work. A
dynamic 2-dimensional array pointed to by an int** can work. There
are probably several more approaches that can work. All you need is
the correct code for the approach you choose.
<<Remove the del for email>>