Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Arrays and Functions (how to clean up code)

2 views
Skip to first unread message

x

unread,
Nov 2, 2009, 12:19:07 PM11/2/09
to
Hello,

Apparently I have a strange way of writing C. For example, here
is a short program showing how I use arrays in functions:

#include <stdio.h>
#include <stdlib.h>

void initialize(int mx, int meqn, double (*p_q)[meqn]);

int main(void) {

int mx = 20,i;
int meqn = 3;
int d1[20];

double q[mx][meqn];
double (*p_q)[meqn];
p_q=q;


initialize(mx, meqn, q);

for (i=0;i<mx;i++){
printf(" i %3d q[i][0] %15.7e\n",i, q[i][0]);
d1[i]=i;
}

return(0);

}

void initialize(int mx, int meqn, double (*p_q)[meqn]){

int i;
double *q;
q = (double *)p_q;


for (i=0;i<mx;i++){
p_q[i][0] = 1.*i;
p_q[i][1] = 2.*i;
p_q[i][2] = 3.*i;
}

}


I was told this was a terrible way to program with unnecessary
variables, etc. I was given the following example of how to clean up
my code and be more efficient in my programming and use dynamic memory
allocation to boot:

#include <stdio.h>
#include <stdlib.h>

void initialize(double p_q[][3], int , int );

int main(void) {

double **p_q;


int mx = 20,i;
int meqn = 3;
int d1[20];

p_q = malloc(sizeof(double)*mx*meqn);

initialize(p_q, mx, meqn);

for (i=0;i<mx;i++){
printf(" i %3d p_q[i][0] %15.7e\n",i, p_q[i][0]);
d1[i]=i;
}

return(0);

}

void initialize(double p_q[][3], int mx, int meqn){

int i;

for (i=0;i<mx;i++){
p_q[i][0] = 1.*i;
p_q[i][1] = 2.*i;
p_q[i][2] = 3.*i;
}

}


The problem is that while this second program compiles (with a
warning), it does not run. In fact, it gives a bus error.

So my question is 2-fold: what is wrong with the second program? and
what is the optimal way to write a program like this? Keep in mind
this is a simplified form of a much more sophisticated program
(several thousand lines of code). My thanks in advance.
--
comp.lang.c.moderated - moderation address: cl...@plethora.net -- you must
have an appropriate newsgroups line in your header for your mail to be seen,
or the newsgroup name in square brackets in the subject line. Sorry.

Dag-Erling Smørgrav

unread,
Nov 2, 2009, 3:00:59 PM11/2/09
to
x <jbu...@cims.nyu.edu> writes:
> double **p_q;
> /* ... */
> p_q = malloc(sizeof(double)*mx*meqn);
> /* ... */

> for (i=0;i<mx;i++){
> printf(" i %3d p_q[i][0] %15.7e\n",i, p_q[i][0]);
> d1[i]=i;
> }

The problem is that p_q is not a two-dimensional array, but a pointer to
an array of pointers to double. It can be used as a two-dimensional
array if each of those pointers points to an array of doubles. You'd
have to do something like this instead of the single malloc() call:

p_q = malloc(sizeof(double *) * mx);
for (i = 0; i < mx; ++i)
p_q[i] = malloc(sizeof(double) * meqn);

DES
--
Dag-Erling Smørgrav - d...@des.no

0 new messages