|
-
March 24th, 2004, 08:50 PM
#1
Pointers and Arrays
I have to write the function vec_to_mat (int *v, int *mat, int n); v is a pointer to the beginning of an integer array (vector) with n x n elements stored in column-major representation (see below for explanation). The function should copy the elements from v to mat (which is a matrix of size n x n). From example,
If v is {1, 2, 3, 4, 5, 6, 7, 8, 9}, the value of mat should be,
1 4 7
2 5 8
3 6 9
The values 1, 2, and 3 go down the first column of matrix mat, and then 4, 5, 6 goes down the second column and so on.
This is what I have so far but it's giving me a compiler error:
Code:
#include<stdio.h>
#include<conio.h>
main()
{
vector_to_matrix ( int * vector , int * matrix , int row_length )
{
int i , j , k;
int column_length = row_length;
i = k = 0;
while ( i < row_length )
{
j = 0;
while ( j < column_length )
{
matrix [(row_len * j++) + i ] = vector [ k ++ ];
}
i++;
}
return 0;
getch()
}
BTW, I have to use pointer arithmetic (not array subscripting) to visit the array elements. Someone, please help me
-
March 25th, 2004, 06:28 AM
#2
main()
{
vector_to_matrix ( int * vector , int * matrix , int row_length )
{
int i , j , k;
int column_length = row_length;
i = k = 0;
while ( i < row_length )
{
j = 0;
while ( j < column_length )
{
matrix [i][j] = vector [ k ++ ];
}
i++;
}
return 0;
getch()
}
Caronte
Si tiene solución... ¿por qué te preocupas?
Si no tiene solución... ¿por qué te preocupas?
-
March 25th, 2004, 07:02 AM
#3
Re: Pointers and Arrays
Originally posted by sanman10535
This is what I have so far but it's giving me a compiler error:
Are you trying to define a function vector_to_matrix ? If yes, it needs to have a return value (e.g. void) and you should better define it outside of your main function.
Second thing: matrix must be an int**, i.e. an arrray of arrays of ints.
-
March 26th, 2004, 01:06 PM
#4
I haven't tested this but, assuming contiguous memory:
Code:
void vector_to_matrix ( int * vector , int * matrix , int row_length )
{
int i,j;
int column_length = row_length;
for(i = 0; i < row_length; i++)
for(j = 0; j < column_length; j++)
matrix + column_length * i + j = vector++;
}
just a guess tho.
A matrix in memory looks like a vector
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|