Passing a 2d array into a function
I'm a bit confused at how I would go about this. I'm trying to pass the
dynamic 2D matrix created in the main function to another function
(create_hadamard_matrix) which fills it up with what I want. (The other
function is implemented in another document)
It works when the matrix is created inside the 'create_hadamard_matrix'
function, but when I pass it in from main the result is random characters.
Main Document:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "hadamard.h"
int main(void)
{
int N,i;
printf("input N for matrix size ");
scanf("%d",&N);
char **h = (char**) malloc(N * sizeof(char*));
for ( i = 0; i < N; i++ )
{
h[i] = (char*) malloc(N * sizeof(char));
}
void create_hadamard_matrix(char** h, int N);
int ind,indr,indc;
for (indr=0; indr<N; indr++)
{
for (indc=0; indc<N; indc++)
{
printf("%c",h[indr][indc]);
}
printf("\n");
}
}
Header Document
// create the hadamard matrix
void create_hadamard_matrix(char** h, int N);
Implementation in separate .c file
create_hadamard_matrix(char** h, int N)
{
//initialize indexes
int ind,indr,indc;
for (ind=1;ind<=N;ind*=2)
{
// find the half length of H matrix for this iteration
int sideHalf=ind/2;
//for n=1 H matrix
if (ind==1)
{
matrix[0][0]='1';
}
else
{
//put in values in bottom left of new H matrix
for (indr=0; indr<sideHalf; indr++)
{
for (indc=0; indc<sideHalf; indc++)
{
matrix[indr+sideHalf][indc]=matrix[indr][indc];
}
}
//put in values in top right of new H matrix
for (indr=0; indr<sideHalf; indr++)
{
for (indc=0; indc<sideHalf; indc++)
{
matrix[indr][indc+sideHalf]=matrix[indr][indc];
}
}
//put in values in bottom right of new H matrix
for (indr=0; indr<sideHalf; indr++)
{
for (indc=0; indc<sideHalf; indc++)
{
//invert characters
if (matrix[indr][indc]=='1')
{
matrix[indr+sideHalf][indc+sideHalf]='0';
}
else
{
matrix[indr+sideHalf][indc+sideHalf]='1';
}
}
}
}
}
return 0;
}
No comments:
Post a Comment