Modifying values in pointers in struct via function

Hi,

I'm trying to pass a struct with 2d array pointers into a function which would change the values specific cells in the array. refer to the sample code:

From header:
1
2
3
4
5
6
7
8
9
typedef struct part_pairs
{
	int** pairs;
	double** dis_pair;
	double** h_pair;
	double** k_pair;
	double** g_pair;

};


Function Code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
void link_list( part_pairs *y...... ) // pointers were created in prior funct
{	int i, n_allocate = 60;
	y->pairs = new int*[n_allocate];
	for (i = 0; i < n_allocate; ++i) y->pairs[i] = new int[n_cp]();

	y->dis_pair = new double*[n_allocate];
	for (i = 0; i < n_allocate; ++i) y->dis_pair[i] = new double[n_cp]();

	y->h_pair = new double*[n_allocate];
	for (i = 0; i < n_allocate; ++i) y->h_pair[i] = new double[n_cp]();

	y->k_pair = new double*[n_allocate];
	for (i = 0; i < n_allocate; ++i) y->k_pair[i] = new double[n_cp]();

	y->g_pair = new double*[n_allocate];
	for (i = 0; i < n_allocate; ++i) y->g_pair[i] = new double[n_cp]();

**** other codes not involving y ****
	for (lz = 1; lz < (ncz + 1); lz++){
		for (ly = 1; ly < (ncy + 1); ly++){
			for (lx = 1; lx < (ncx + 1); lx++){
			j1 = lx + (ly - 1)*ncx + (lz - 1)*nsheet;

			cell(y, j1,...); // function cal; unable to use "&y"

			}
		}
	}

	return;

} // end function link_list 


1
2
3
4
5
6
7
8
void cell(part_pairs *y, ......)
{
	y->pairs[n_pairs[i]][i] = j;
	y->dis_pair[n_pairs[i]][i] = dis;
	y->h_pair[n_pairs[i]][i] = -deta_x;
	y->k_pair[n_pairs[i]][i] = -deta_y;
	y->g_pair[n_pairs[i]][i] = -deta_z;
} // end function cell 



The problem is that the output of the arrays are wrong when returned out of the two functions.

The code is truncated to the gist, I hope it's sufficient information to advise me on what i should modify.

Thank you.

Last edited on
> The code is truncated to the gist, I hope it's sufficient information to
> advise me on what i should modify.
those snips don't compile, so can't run the program and input whatever it needs to shows the wrong output (which also don't know what should be).
It should be able to reproduce the exact same problem that you're having, anything less than that is useless.


> cell(y, j1,...); // function cal; unable to use "&y"
don't fall on the «doesn't work, add or remove * or &» vudú.
I would change the y parameter in link_list() and cell() to be a reference instead of a pointer. Don't pass a pointer unless you expect that it can be null.

In cell(), what is the value of npairs[i][i]? I suspect they aren't what you think. Try examining the value of the arrays before you return from link_list().
thanks for the tip, dhayden, I'll look into references. Is there a sample code that I can refer to that is similar to my issue?

Thanks again!
Topic archived. No new replies allowed.