I have two two-dimensional arrays, and i don’t know why, or how, the addresses of two elements one from each array, coincide..
Here’s the source code:
#include <stdio.h>
int main()
{
int i,j,m,n,o,p,*ptr;
printf("Enter dimension of 1st matrix: ");
scanf("%d * %d",&m,&n);
printf("Enter dimension of 2nd matrix: ");
scanf("%d * %d",&o,&p);
int *a[m][n];
int *b[o][p];
if (n!=o) return 0;
printf("\nEnter 1st matrix:\n");
for (i=0;i<m;i++)
for (j=0;j<n;j++)
{ printf("%d ",(a+i*(n-1)+i+j)); scanf("%d",(a+i*(n-1)+i+j)); }
printf("\nEnter 2nd matrix:\n");
for (i=0;i<o;i++)
for (j=0;j<p;j++)
{ printf("%d ",(b+i*(p-1)+i+j)); scanf("%d",(b+i*(p-1)+i+j)); }
/*Printing the matrices*/
puts("");puts("");
for (i=0;i<m;i++)
{for (j=0;j<n;j++)
{ ptr = (a+i*(n-1)+i+j);
printf(" %d ",*ptr); } puts("");}puts("");
for (i=0;i<o;i++)
{for (j=0;j<p;j++)
{ ptr = (b+i*(p-1)+i+j);
printf(" %d ",*ptr); } puts("");}
}
And here’s a print screen;
Due to this, i have been getting errors in a simple program to calculate the product of two matrices. The question is, is this usual? Shouldn’t the compiler or the OS have taken care of this?
Also, why do i have to do ptr = (a+i*(n-1)+i+j); printf(" %d ",*ptr);?
Why won’t printf(" %d ",*(a+i*(n-1)+i+j)); work?
First of all,
aandbare arrays of pointers, and the pointers are never initialized.My guess is that it was meant to read:
(The rest of the code would need to be changed accordingly.)
Secondly, you’re treating pointers as
ints(e.g. in%d). Bear in mind that a pointer can be wider than anint. For example, on my platform pointers are 64-bit andintsare 32-bit.