0

Please edit the title if you know the actual problem behind this. I'm facing a very strange behavior with pointers in C.

Version 1 (What I want but the output is not what I expect):

void *partial_evolve(void * pars) { evolve_pars *p = (evolve_pars*)pars; unsigned char *in = *p->grid_in; unsigned char *out = *p->grid_out; for (int t = 0; t < p->time_steps; ++t) { for (int y = 0; y < p->dim_y; ++y) for (int x = p->start_x; x < p->end_x; ++x) evolve(in, out, p->dim_x, p->dim_y, x, y); swap(&in, &out); pthread_barrier_wait(&barrier); } } 

Version 2 (The output is right but I have to use two waits which I do not want):

void *partial_evolve(void * pars) { evolve_pars *p = (evolve_pars*)pars; for (int t = 0; t < p->time_steps; ++t) { for (int y = 0; y < p->dim_y; ++y) for (int x = p->start_x; x < p->end_x; ++x) evolve(*p->grid_in, *p->grid_out, p->dim_x, p->dim_y, x, y); pthread_barrier_wait(&barrier); swap(p->grid_in, p->grid_out); pthread_barrier_wait(&barrier); } } 

The input struct that I use is:

typedef struct { unsigned int dim_x; unsigned int dim_y; unsigned char **grid_in; unsigned char **grid_out; unsigned int start_x; unsigned int end_x; unsigned int time_steps; int is_master_thread; } evolve_pars; 

The swap function:

void swap(unsigned char **a, unsigned char **b) { unsigned char *tmp = *a; *a = *b; *b = tmp; } 

Regardless of the rest of the code, the pointer operation of the partial_evolve function in both cases should behave the same. Any ideas?

4
  • Why use void *? That means losing information for the compiler Commented May 11, 2014 at 8:06
  • @EdHeal: It is probably a callback function. Commented May 11, 2014 at 8:07
  • @leppie - Perhaps - but not specified in the question Commented May 11, 2014 at 8:08
  • It's a thread. It has to be void *. Besides that, there is no problem for using void * as long as you cast it right. Am I right on this? Commented May 11, 2014 at 8:09

1 Answer 1

1

In the first version, the swap() function is called with the address of 2 local pointers.

swap(&in, &out); 

In the second version, the parameters are part of the structure

swap(p->grid_in, p->grid_out); 
Sign up to request clarification or add additional context in comments.

6 Comments

What is the problem with that? Could you explain more please?
@Hamid The problem is that you act on local (temporary ot the context) data and not changing the actual data inside your evolve_pars struct
I really do not understand what you mean. Do you mean the swap function is not swapping the pointers?
I'm pretty sure the result of swap on both cases is the same.
The first swap does not change the contents of the struct; you cannot see changes in the calling function.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.