LinuxQuestions.org
Review your favorite Linux distribution.
Home Forums Tutorials Articles Register
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices


Reply
  Search this Thread
Old 05-26-2010, 07:05 AM   #1
smp
LQ Newbie
 
Registered: Jun 2009
Posts: 21

Rep: Reputation: 0
filling 2D array with the help of 1D array in C


Hi,

(I am using vector() and matrix() functions from "Numerical recipes in C".)

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:

Code:
 :
  :
  #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
 
Old 05-26-2010, 09:08 AM   #2
bartonski
Member
 
Registered: Jul 2006
Location: Louisville, KY
Distribution: Fedora 12, Slackware, Debian, Ubuntu Karmic, FreeBSD 7.1
Posts: 443
Blog Entries: 1

Rep: Reputation: 48
Please post compileable code...

The problem is most likely in how memory is allocated or freed, or in the type of data structure that you're trying to allocate memory for... and you haven't posted any of that.

Try to assemble the smallest piece of compileable code which demonstrates the problem that you're having... often, the process of isolating the problem this way will uncover the source of the memory issue.
 
Old 05-26-2010, 10:30 AM   #3
brazilnut
Member
 
Registered: Nov 2007
Posts: 113

Rep: Reputation: 16
not sure because as bartonski states, there ain't enough code to compile...

but shouldn't 'k' be initialised to '0', otherwise it is trying to access shift[100],
whereas i'd say it only ranged from 0 - 99
 
Old 05-26-2010, 11:57 PM   #4
smp
LQ Newbie
 
Registered: Jun 2009
Posts: 21

Original Poster
Rep: Reputation: 0
Quote:
Please post compileable code...
This is my whole code:

Code:
#include<stdio.h>
#include<math.h>
#include<stdlib.h>
#include"nrutil.c"

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


float ran1(long *idum);        // This is random no. generator from Numerical Recipe

int main()
{
  long *idum;
  int i,k,r;
  long j;
  float n1,n2,n3;
 
  
  float *dx, *dy, *shift,**sensor_matrix;
  shift=vector(1,size);
  dx=vector(nl,nh);
  dy=vector(nl,nh);
  sensor_matrix=matrix(nl,nh,nl,nh);

 
  //________________ dx _________________________

  j=-5;
  idum = &j; 
  for(i=1;i<=size;i++)
   {
     n1=ran1(idum);
     n2=n1-0.5;
     n3=n2*10.0;
         
     dx[i]=n3;
   }

  
  //__________________ dy ________________________

  j=-9;
  idum = &j; 
  for(i=1;i<=size;i++)
   {
     n1=ran1(idum);
     n2=n1-0.5;
     n3=n2*10.0;
  
     dy[i]=n3;
   }

  //___________________ shift _____________________

  for(i=1;i<=size;i++)
   {
      shift[i]=sqrtf( powf(dx[i],2.0) + powf(dy[i],2.0) );
   }

  //___________________ Sensor Matrix ______________


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

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

              k++;

           }
     }
 //_________________________________________________

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


  return 0;

}
 
Old 05-27-2010, 12:13 AM   #5
graemef
Senior Member
 
Registered: Nov 2005
Location: Hanoi
Distribution: Fedora 13, Ubuntu 10.04
Posts: 2,379

Rep: Reputation: 148Reputation: 148
Arrays in C count from 0 to size-1, and so your loops need changing, nl should be initialised to 0 and the loop should be i<nh (rather than i <=nl)
There may be other errors along these lines such as size. But so long as you understand how the C index works you should be able to figure them out.

Last edited by graemef; 05-27-2010 at 12:15 AM. Reason: different slant on the logic
 
0 members found this post helpful.
Old 05-27-2010, 12:33 AM   #6
smp
LQ Newbie
 
Registered: Jun 2009
Posts: 21

Original Poster
Rep: Reputation: 0
Hey, I got my mistake:

I wanted to create 100 "dx" and 100 "dy" values. So I get 100 "shift" values.
so instead of vector dx[1...100] I was writing dx[1...10] since I was setting nl=1 and nh=10. Same thing I was doing for "dy".

This was my mistake:

Quote:

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


Also, I changed the sensor_matrix[][] indices for avoiding confusion:

Quote:

#define size 100

#define nl 1
#define nh 100

#define nrl 1
#define nrh 10
#define ncl 1
#define nch 10
:
:
sensor_matrix=matrix(nrl,nrh,ncl,nch);

Thanks and Regards,
smp
 
Old 05-27-2010, 12:44 AM   #7
smp
LQ Newbie
 
Registered: Jun 2009
Posts: 21

Original Poster
Rep: Reputation: 0
Quote:
Originally Posted by graemef View Post
Arrays in C count from 0 to size-1, and so your loops need changing, nl should be initialised to 0 and the loop should be i<nh (rather than i <=nl)
There may be other errors along these lines such as size. But so long as you understand how the C index works you should be able to figure them out.
Have you heard about "Numerical Recipes in C"?
Please read this book. Then you can see that 0-offset is not necessary for C arrays. We can have unit-offset too in C arrays. and that is what I am using in my code....When we are dealing with matrices, unit-offset is advisable; when we are dealing with coefficients of polynomials, then zero-offset is best. It depends on the problem you are handling.
 
Old 05-27-2010, 09:08 AM   #8
graemef
Senior Member
 
Registered: Nov 2005
Location: Hanoi
Distribution: Fedora 13, Ubuntu 10.04
Posts: 2,379

Rep: Reputation: 148Reputation: 148
Arrays in the C language are zero based, this is to allow pointer arithmetic.

This doesn't stop functions from being written that provide a different approach which is what I suspect you have. However, if you are using such a suite of functions then I would expect that all your access would need to be through these functions. Given that C doesn't provide operator overloading I would suggest that your use of the subscript [] is erroneous.
 
Old 05-28-2010, 04:27 PM   #9
bartonski
Member
 
Registered: Jul 2006
Location: Louisville, KY
Distribution: Fedora 12, Slackware, Debian, Ubuntu Karmic, FreeBSD 7.1
Posts: 443
Blog Entries: 1

Rep: Reputation: 48
In the 'for what it's worth' department:

nrutil.c can be found here:

http://www.nr.com/pubdom/nrutil.c.txt

I was going to go home and try to compile this, but you've already found the error (I may try to compile it anyway, just for grins).
 
Old 05-28-2010, 04:43 PM   #10
johnsfine
LQ Guru
 
Registered: Dec 2007
Distribution: Centos
Posts: 5,286

Rep: Reputation: 1197Reputation: 1197Reputation: 1197Reputation: 1197Reputation: 1197Reputation: 1197Reputation: 1197Reputation: 1197Reputation: 1197
Quote:
Originally Posted by smp View Post
Hey, I got my mistake
That all seems to be inconsistent with the "I get segmentation fault here" indication in your first post. IIUC, the problem turns out to be in part of the code you didn't include in your first post.

You figured it out without our help this time. I guess that lets you learn more than if you actually needed our help.

But if some time you actually need help, remember that posting a code fragment with a guess about the problem generally won't get you any real help. You need to post enough context. Usually you need to post an entire testable program.

Quote:
Originally Posted by graemef View Post
Arrays in the C language are zero based, this is to allow pointer arithmetic.

This doesn't stop functions from being written that provide a different approach which is what I suspect you have. However, if you are using such a suite of functions then I would expect that all your access would need to be through these functions.
But a pointer in C doesn't need to point exactly to the object that will be accessed by that pointer.

The suite of functions is used for all the allocation and deallocation operations, so that ordinary C can be used for all the access.

For a simple example:
int hidden_array[10];
int *fake_array = hidden_array-1;

Then use fake_array as if it were an array whose element are numbered 1 to 10. It all works.

Obviously accessing element 0 or 11 of fake_array is unsound, but that is no different than element -1 or 10 of hidden_array.

The suite of functions hides the allocation of the real array as well as the pointer adjustment before returning the result to the caller as well as the reverse pointer adjustment during deallocation.

Last edited by johnsfine; 05-28-2010 at 04:46 PM.
 
Old 05-29-2010, 12:05 AM   #11
graemef
Senior Member
 
Registered: Nov 2005
Location: Hanoi
Distribution: Fedora 13, Ubuntu 10.04
Posts: 2,379

Rep: Reputation: 148Reputation: 148
Quote:
Originally Posted by johnsfine View Post
For a simple example:
int hidden_array[10];
int *fake_array = hidden_array-1;

Then use fake_array as if it were an array whose element are numbered 1 to 10. It all works.
That makes sense, thanks.
 
Old 05-30-2010, 03:55 AM   #12
ArthurSittler
Member
 
Registered: Jul 2008
Distribution: Slackware
Posts: 124

Rep: Reputation: 31
Numerical Recipes In C-TRAN

I actually do have a copy of Numerical Recipes In C by Press et al. I recommend that you take those recipes with at least a grain of salt. It is apparent to me and many other reviewers of the book that the authors were not, in fact, very experienced with C. From the array indexing ranges you cited, I and many other people I talked with about that book concluded that the authors' programming background was probably in FORTRAN. C always indexes an n-element array from 0 to n-1, not from 1 to n. If you demand to index from 1 to n, you need to declare your arrays as size n+1 in each dimension, which wastes a lot of space because you are allocating space for the 0 row and the 0 column of every other row in the array. Most C programmers find artificially reindexed arrays with loop indexes from 1 to n with array indexes artificially offset to be poor coding style at best.

There is actually a common name for such reindexing and certain other related artifacts used in C. We call it C-TRAN. It is considered a pejorative term.

Your segmentation fault occurred when your array indexes put your access outside of the space allocated for the array. In some cases, this could happen quietly with far worse results. Memory pages in Linux are 4kiB. Memory protection is implementable only with a granularity of that page size. If your array were small enough to not extend outside of your page, and if you had other local variables past the top of your array, you could easily be stomping all over other data without causing a segmentation fault. That is the sort of bug that could take a long time to locate.

At least some of the algorithms in the cited book are known to be unreliable. The particular case I know about involves Bessel functions. It may fail to find an answer and return garbage value without any error indication. I believe there are other instances where the algorithm either performs very poorly (i.e., slower than the standard algorithms) or actually returns incorrect results. But the book ended up on my less preferred list when I saw the 1-based indexing and proof of the failures in the Bessel functions.

I can't say that the book over all is not useful. I just want to warn you that the programming practices and algorithms that you find in a published book may not be the best or even necessarily correct.
 
Old 05-30-2010, 05:10 AM   #13
graemef
Senior Member
 
Registered: Nov 2005
Location: Hanoi
Distribution: Fedora 13, Ubuntu 10.04
Posts: 2,379

Rep: Reputation: 148Reputation: 148
Quote:
Originally Posted by ArthurSittler View Post
If you demand to index from 1 to n, you need to declare your arrays as size n+1 in each dimension, which wastes a lot of space because you are allocating space for the 0 row and the 0 column of every other row in the array.
As johnsfine pointed out you don't have to have this wasted space, just use an overlay array with an initial negative offset. For a matrix it will be offset (negatively) by the number of columns plus one, and I assume this can be done in more dimensions but I don't see much gain from such an approach.

But I agree introducing such a concept in a book doesn't gain much and it would be at the expense of their credibility.
 
  


Reply



Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
bash: use file as input into array, parse out other variables from array using awk beeblequix Linux - General 2 11-20-2009 10:07 AM
[SOLVED] array of array in Fortran 90 aihaike Programming 2 07-13-2009 04:34 AM
Bash Variable Array, Trying to add another value into the array helptonewbie Linux - Newbie 6 03-02-2009 11:18 PM
[perl] copying an array element into another array s0l1dsnak3123 Programming 2 05-17-2008 01:47 AM
PERL: Size of an array of an Array inspleak Programming 2 03-10-2004 02:24 PM

LinuxQuestions.org > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 08:21 PM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration