filling 2D array with the help of 1D array


smp
05-26-2010, 05:30 AM
Hi,

I am using vector() and matrix() functions.

There are 100 numbers to be stored in 2D array of 10 rows and 10 columns.
100 numbers are stored in a 1D array.

I get "segmentation fault" at the line indicated in the segment of my code below:

:
:
#define size 100
#define nl 1
#define nh 10

:
:
float **sensor_matrix, *shift;
shift=vector(1,size);
sensor_matrix=matrix(nl,nh,nl,nh);
:
:


k=1;
for(i=nl;i<=nh;i++)
{

for(j=nl;j<=nh;j++)
{
sensor_matrix[i][j]=shift[k]; // I get segmentation fault here

k++;
}
}
:
:
free_matrix(sensor_matrix,nl,nh,nl,nh);
free_vector(shift,1,size);


Any help will be appreciated.

Thanks and Regards
smp

davekw7x
05-26-2010, 09:13 AM
I am using vector() and matrix() functions.From the Numerical Recipes C distribution, right?


I get "segmentation fault"...
Any help will be appreciated.
...
How about showing us the complete program? If it's too big to post (or for some reason you don't or can't post the entire program), then make a small (complete) program that shows your problem.

For example, the following gives me no problems:

/*
Numerical Recipes (Version 2) C program
davekw7x
*/

#include <stdio.h>

/* Make sure it checks function prototypes */
#define NRANSI
#include "nr.h"
#include "nrutil.h"

int main()
{
int i, j, k;
int nl = 1; /* Start at index value 1, not zero */
int nh = 10; /* Number of rows and columns */
int size = nh*nh; /* Number of rows times number of columns */

float **sensor_matrix;
float *shift;

/* Initialize the 1-D array */
shift = vector(1, size);
for (i = 1; i <= size; i++) {
shift[i] = i;
}


/* Copy 1-D contents to 2-D rows and columns */
sensor_matrix = matrix(nl, nh, nl, nh);
k = 1;
for (i = nl; i <= nh; i++) {
for (j = nl; j <= nh; j++) {
sensor_matrix[i][j] = shift[k];
k++;
}
}

/* Print 2-D array contents */
for (i = nl; i <= nh; i++) {
printf("Row %2d:", i);
for (j = nl; j <= nh; j++) {
printf("%6.1f",sensor_matrix[i][j]);
}
printf("\n");
}

free_matrix(sensor_matrix, nl, nh, nl, nh);
free_vector(shift, 1, size);

return 0;
}


Output (compiled with GNU gcc):

Row 1: 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10.0
Row 2: 11.0 12.0 13.0 14.0 15.0 16.0 17.0 18.0 19.0 20.0
Row 3: 21.0 22.0 23.0 24.0 25.0 26.0 27.0 28.0 29.0 30.0
Row 4: 31.0 32.0 33.0 34.0 35.0 36.0 37.0 38.0 39.0 40.0
Row 5: 41.0 42.0 43.0 44.0 45.0 46.0 47.0 48.0 49.0 50.0
Row 6: 51.0 52.0 53.0 54.0 55.0 56.0 57.0 58.0 59.0 60.0
Row 7: 61.0 62.0 63.0 64.0 65.0 66.0 67.0 68.0 69.0 70.0
Row 8: 71.0 72.0 73.0 74.0 75.0 76.0 77.0 78.0 79.0 80.0
Row 9: 81.0 82.0 83.0 84.0 85.0 86.0 87.0 88.0 89.0 90.0
Row 10: 91.0 92.0 93.0 94.0 95.0 96.0 97.0 98.0 99.0 100.0



Regards,

Dave