-
Quick question
Quick question about 2D arrays and pointers. Trying to input information into a 4x4 array and when I use the numbers 1-16 it repeats the numbers every time it goes to a new row. i.e.
1 2 3 4
4 5 6 7
7 8 9 10
10 11 12 13
instead of storing the numbers 1-16.
This is the code I'm trying, been to help websites and still having trouble.
Code:
void read_matrix(int *m)
{
int *p;
for(p = m; p < m + 16; p++)
scanf("%d", p);
}
What I was trying to do was treat it like a single dimension array as that is what my textbook said could work. Any suggestions would be great.
-
Code:
void read_matrix(int ar[][4]) {
int i,j;
for(i = 0; i< 4; i++)
for(j = 0; j<4; j++)
scanf("%d",&ar[i][j]);
}
hope this helps
-
Forgot to mention that we can only use pointer arithmetic, not subscripting. That's where I'm having the trouble :(
-
just cast the array to a pointer to int.
Code:
void read_matrix(int m[][4])
{
int *p = (int*)m, *end =p+16;
while(p != end)
{
scanf("%d", p++);
}
}
the other way is to do this
Code:
void read_matrix(int *m)
{
int *p = m, *end =p+16;
while(p != end)
{
scanf("%d", p++);
}
}
int main()
{
int array[4][4];
read_matrix(*array);
return 0;
}
either way, but the first way is probably better as it blinds the user to how the function works.
the other way of treating it as a 2D array using pointer arithmetic is abit harder so i won't post unless u want to know.
-
>>What I was trying to do was treat it like a single dimension array as that is what my textbook said could work. <<
Not really, you'll find. Flattening the array isn't good practice.
-
Heh, pointers to multi-dimension arrays really sorts the men from the boys IMO
Scratch your noggin over this for a while...
Code:
#include <stdio.h>
#include <string.h>
void read_matrix(int ar[][4]) {
int i,j;
for(i = 0; i< 4; i++) {
for(j = 0; j<4; j++) {
scanf("%d",&ar[i][j]);
}
}
}
void read_matrix2(int (*arr)[4]) {
int (*p)[4]; /* point to a whole row of arr */
int *q; /* point to the start of a row of arr */
for ( p = arr ; p < arr + 4 ; p++ ) {
for ( q = *p ; q < *p + 4 ; q++ ) {
scanf("%d",q);
}
}
}
void print_array ( int arr[][4] ) {
int i,j;
for(i = 0; i< 4; i++) {
for(j = 0; j<4; j++) {
printf("%d ",arr[i][j]);
}
printf( "\n" );
}
printf( "\n" );
}
int main ( ) {
int array[4][4];
read_matrix(array);
print_array(array);
read_matrix2(array);
print_array(array);
return 0;
}