[prog] mutlitdimensional arrays in C
aec
brat at magma.ca
Sat Oct 9 10:47:35 EST 2004
Hi
I have a two part exercise in my C book.
1. write a program that takes a 2d array (4row 5col) and
transposes it to a 5 row 4 col array.
I used a function that accepts two arrays as its arguments,
----------------------------------------------------------
#include <stdio.h>
void transposeArray(int m[4][5], int n[5][4])
{
int row, column;
printf("\nOriginal array:\n\n");
for (row = 0; row < 4; ++row) { // display the row
for (column = 0; column < 5; ++column) // display the column
printf("%5i", m[row][column]);
printf("\n");
}
for (row = 0; row < 5; ++row) { // convert the array to [5][4]
for (column = 0; column < 4; ++column)
n[row][column] = m[column][row];
}
printf("\nTransposed array:\n\n");
for (row = 0; row < 5; ++row) { // display the row
for (column = 0; column < 4; ++column) // display the column
printf("%5i", n[row][column]);
printf("\n");
}
}
int main(void)
{
int m[4][5] = {
{1,2,3,4,5},
{6,7,8,9,10},
{11,12,13,14,15},
{16,17,18,19,20}
};
int n[5][4];
transposeArray(m,n);
return 0;
}
---------------------------------------------------------------
There is something I dont like, and that is the function does
the printing of the array, I redid this program and placed the
printing into main, and had the function return the new array
to main.
This gave me some gcc warnings but the program did compile and run
ex.8.12.c: In function `transposeArray':
ex.8.12.c:15: warning: return makes integer from pointer without a cast
I am not sure what these warnings mean, I havent done pointers yet
in the book. Also, all my types are ints, so im confused about the
"cast" in the error.
I suspect that possibly it is the wrong way to pass an array back to main?
here is the second version that works, but gives the gcc errors:
------------------------------------------------------------------
#include <stdio.h>
int transposeArray(int m[4][5], int n[5][4])
{
int row, column;
for (row = 0; row < 5; ++row) { // convert the array to [5][4]
for (column = 0; column < 4; ++column)
n[row][column] = m[column][row];
}
return n;
}
int main(void)
{
int m[4][5] = {
{1,2,3,4,5},
{6,7,8,9,10},
{11,12,13,14,15},
{16,17,18,19,20}
};
int n[5][4];
int row, column;
transposeArray(m,n);
printf("\nOriginal array:\n\n");
for (row = 0; row < 4; ++row) { // display the row
for (column = 0; column < 5; ++column) // display the column
printf("%5i", m[row][column]);
printf("\n");
}
printf("\nTransposed array:\n\n");
for (row = 0; row < 5; ++row) { // display the row
for (column = 0; column < 4; ++column) // display the column
printf("%5i", n[row][column]);
printf("\n");
}
return 0;
}
-------------------------------------------------------------------
So, although I have technically done what the author wanted, gcc
errors bug me and Id like to know whats the cause.
--
Angelina Carlton
More information about the Programming
mailing list