473,326 Members | 2,732 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,326 software developers and data experts.

I've forgotten my C: passing 2-D matrices


There was a time when all I programmed was C. I thought I'd never
forget it; not the basics anyway. Therefore I find it very upsetting
that this is giving me a segfault:

#include <stdio.h>
double foo[ 2 ][ 3 ] = {{1., 2., 3.}, {4., 5., 6.}};
int main( void ) {
int i, j;
double **r;
r = foo;
for ( i = 0; i < 2; ++i ) {
for ( j = 0; j < 3; ++j ) {
printf( "%f\t", r[ i ][ j ] );
}
printf( "\n" );
}
return 0;
}

More generally, I want to pass foo as the argument to a function
bar(double **, int n_rows, int n_cols), but either bar(foo, 2, 3)
or bar((double **)foo, 2, 3) result in another segfault. I realize
that I am making an elementary mistake, but for the life of me I
can no longer see it. Please someone remind me of what I should
do.

TIA!

jill

--
To s&e^n]d me m~a}i]l r%e*m?o\v[e bit from my a|d)d:r{e:s]s.

Nov 14 '05 #1
8 1770
> More generally, I want to pass foo as the argument to a function
bar(double **, int n_rows, int n_cols), but either bar(foo, 2, 3)
or bar((double **)foo, 2, 3) result in another segfault. I realize
that I am making an elementary mistake, but for the life of me I
can no longer see it. Please someone remind me of what I should
do.


I've had little luck unless I declare foo as:

double **foo;

and malloc the appropriate rows and columns. This data structure is
then easily passed to a function expecting a paramter of type double **

Example:

foo = (double **)malloc((height) * sizeof(double*));
for(i=0; i<height; i++)
{
foo[i] = (double *)malloc((width) * sizeof(double));
}

The values of matrix are accessible by 'foo[y][x]' (y ranges from 0 to
height-1, x ranges from 0 to width-1)

foo is also passable to function bar.

....waiting for the gurus here to slice me down... =)

Nov 14 '05 #2
In article <d6**********@reader1.panix.com>
J Krugman <jk*********@yahbitoo.com> wrote:
double foo[ 2 ][ 3 ] = [snippage] ...
[and now] I want to pass foo as the argument to a function
bar(double **, int n_rows, int n_cols) ...


See the comp.lang.c FAQ, in particular question 6.18.
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: forget about it http://web.torek.net/torek/index.html
Reading email is like searching for food in the garbage, thanks to spammers.
Nov 14 '05 #3

"J Krugman" <jk*********@yahbitoo.com> wrote in message
news:d6**********@reader1.panix.com...

There was a time when all I programmed was C. I thought I'd never
forget it; not the basics anyway. Therefore I find it very upsetting
that this is giving me a segfault:

#include <stdio.h>
double foo[ 2 ][ 3 ] = {{1., 2., 3.}, {4., 5., 6.}};
int main( void ) {
int i, j;
double **r;
r = foo;
for ( i = 0; i < 2; ++i ) {
for ( j = 0; j < 3; ++j ) {
printf( "%f\t", r[ i ][ j ] );
}
printf( "\n" );
}
return 0;
}

More generally, I want to pass foo as the argument to a function
bar(double **, int n_rows, int n_cols), but either bar(foo, 2, 3)
or bar((double **)foo, 2, 3) result in another segfault. I realize
that I am making an elementary mistake, but for the life of me I
can no longer see it. Please someone remind me of what I should
do.


double (*r)[3];
Nov 14 '05 #4
In <d6*********@news1.newsguy.com> Chris Torek <no****@torek.net> writes:
In article <d6**********@reader1.panix.com>
J Krugman <jk*********@yahbitoo.com> wrote:
double foo[ 2 ][ 3 ] = [snippage] ...
[and now] I want to pass foo as the argument to a function
bar(double **, int n_rows, int n_cols) ...
See the comp.lang.c FAQ, in particular question 6.18.


Thank you.

What I ended up doing is

#define M 2
#define N 3

/* double foo[ M ][ N ] as before */

int i;
double **dummy;
dummy = ( double ** ) calloc( ( size_t ) M,
( size_t ) sizeof( double * ) );
for ( i = 0; i < M; ++i ) dummy[ i ] = foo[ i ];

bar( dummy, M, N );

Is this the typical way to pass a 2-D array to a function that
takes a pointer-to-pointer, or is there a more clueful approach?

jill

--
To s&e^n]d me m~a}i]l r%e*m?o\v[e bit from my a|d)d:r{e:s]s.

Nov 14 '05 #5
"No Such Luck" <no*********@hotmail.com> writes:
More generally, I want to pass foo as the argument to a function
bar(double **, int n_rows, int n_cols), but either bar(foo, 2, 3)
or bar((double **)foo, 2, 3) result in another segfault. I realize
that I am making an elementary mistake, but for the life of me I
can no longer see it. Please someone remind me of what I should
do.


I've had little luck unless I declare foo as:

double **foo;

and malloc the appropriate rows and columns. This data structure is
then easily passed to a function expecting a paramter of type double **

Example:

foo = (double **)malloc((height) * sizeof(double*));
for(i=0; i<height; i++)
{
foo[i] = (double *)malloc((width) * sizeof(double));
}

The values of matrix are accessible by 'foo[y][x]' (y ranges from 0 to
height-1, x ranges from 0 to width-1)

foo is also passable to function bar.


Casting the result of malloc() is unnecessary and can mask errors.

Here's a better way to do the same thing:

double **foo;

foo = malloc(height * sizeof *foo);
for(i=0; i<height; i++)
{
foo[i] = malloc(width * sizeof *(foo[i]));
}

Note that I've also changed the arguments to the sizeof operators so
they refer to what the destination pointer points to rather than using
the name of the type. This means that if you later decide to use a
type other than double, the malloc() calls will continue to work. If
you change the declaration of foo to "int **foo", but forget to change
"sizeof(double)" to "sizeof(int)", Bad Things can happen.)

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 14 '05 #6
On Mon, 23 May 2005 16:06:15 +0000 (UTC), J Krugman
<jk*********@yahbitoo.com> wrote:

There was a time when all I programmed was C. I thought I'd never
forget it; not the basics anyway. Therefore I find it very upsetting
that this is giving me a segfault:

#include <stdio.h>
double foo[ 2 ][ 3 ] = {{1., 2., 3.}, {4., 5., 6.}};
int main( void ) {
int i, j;
double **r;
r = foo;
for ( i = 0; i < 2; ++i ) {
for ( j = 0; j < 3; ++j ) {
printf( "%f\t", r[ i ][ j ] );
}
printf( "\n" );
}
return 0;
}

More generally, I want to pass foo as the argument to a function
bar(double **, int n_rows, int n_cols), but either bar(foo, 2, 3)
This should result in a syntax error. If it doesn't, you need to up
the warning level of your compiler.
or bar((double **)foo, 2, 3) result in another segfault. I realize
A segfault is one of the better results when you lie to the compiler.
This code says foo[0] is a pointer. It isn't.
that I am making an elementary mistake, but for the life of me I
can no longer see it. Please someone remind me of what I should
do.

TIA!

jill


<<Remove the del for email>>
Nov 14 '05 #7
On Mon, 23 May 2005 17:52:44 +0000 (UTC), J Krugman
<jk*********@yahbitoo.com> wrote:
In <d6*********@news1.newsguy.com> Chris Torek <no****@torek.net> writes:
In article <d6**********@reader1.panix.com>
J Krugman <jk*********@yahbitoo.com> wrote:
double foo[ 2 ][ 3 ] = [snippage] ...
[and now] I want to pass foo as the argument to a function
bar(double **, int n_rows, int n_cols) ...
See the comp.lang.c FAQ, in particular question 6.18.


Thank you.

What I ended up doing is

#define M 2
#define N 3

/* double foo[ M ][ N ] as before */

int i;
double **dummy;
dummy = ( double ** ) calloc( ( size_t ) M,
( size_t ) sizeof( double * ) );


Don't cast the result of calloc or its cousins. It can never help but
can mask a failure to have a prototype in scope for the function.
There is also no need to cast the parameters. The compiler will
coerce them into the correct form if the prototype is in scope.
Furthermore, sizeof evaluates to a size_t so that cast is completely
redundant.

Since you immediately assign values to the area allocated in the next
code, using calloc wastes machine cycles initializing the area to
all-bits-zero. This bit value is not necessarily a valid value for a
pointer but you don't use it anyway.

The recommended idiom is
dummy = malloc(M * sizeof *dummy);
for ( i = 0; i < M; ++i ) dummy[ i ] = foo[ i ];

bar( dummy, M, N );

Is this the typical way to pass a 2-D array to a function that
takes a pointer-to-pointer, or is there a more clueful approach?


Assuming that such an event can be called typical, this looks like a
reasonable way to do it.
<<Remove the del for email>>
Nov 14 '05 #8
> Note that I've also changed the arguments to the sizeof operators so
they refer to what the destination pointer points to rather than using the name of the type. This means that if you later decide to use a
type other than double, the malloc() calls will continue to work. If
you change the declaration of foo to "int **foo", but forget to change "sizeof(double)" to "sizeof(int)", Bad Things can happen.)


Thanks for the more optimized approach. I'll give it a try...

Nov 14 '05 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
by: fivelitermustang | last post by:
I have two matrices allocated dynamically in both directions: matrix x and matrix v. I want to pass these matrices into a function by reference. What I have written down isn't working... can...
3
by: sandwich_eater | last post by:
What is the usual way to declare real (float) vectors and matrices? What ways are there to pass them to them into a function (by ref, by val, pointer) ? this is what I have... const int...
3
by: Prototipo | last post by:
Hi! I need to dynamically create X vectors of matrices (with a known size of 5x5). It's like a three-dimensional matrix with 2 known dimensions and the third unknown. I have something like: ...
2
by: Morgan | last post by:
Thanks to all of you because I solved the problem related with my previous post. I simply made confusion with pointers to pointers and then succeeded passing the reference to the first element...
1
emaghero
by: emaghero | last post by:
Does anybody know an algorithm for the fast multiplication of three n-x-n symmetric matrices? I have an algorithm, which I'm not too pleased with, that does the job. Does anybody know a faster...
9
by: tomamil | last post by:
imagine that you have different matrices with different names and you want to perform the same action with each of them. is it possible to put their names into some array and to create a loop that...
5
by: td0g03 | last post by:
This program adds two square matrices - Algorithm 1-3, Page 35. Change it to implement the generalized algorithm to add two m x n matrices. Matrices, in general, are not square or n x n...
2
by: debiasri | last post by:
I have to devide a matrix in variable no of matrices with each having variable no of rows. Like I have to devide a matrix with dim.9X19 into say 4 matrices with row nos 1,6,6,6 respectively, and I...
3
by: runcyclexcski | last post by:
I have written an image processing app in Matlab which works fine when I analyse images one at a time, but is very slow when I have to analyze thousands of images in a row. So I re-wrote the image...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.