开发者

Passing a struct as a pointer, resulting in a corrupted array?

开发者 https://www.devze.com 2023-02-10 11:56 出处:网络
I have a struct being passed in as a void* pointer void *find_queens(void *args) { I tried to turn this pointer in a usable struct using this

I have a struct being passed in as a void* pointer

void *find_queens(void *args) {  

I tried to turn this pointer in a usable struct using this

struct queens_arg *data = (struct queens_arg *) args;

However, the array that is stored within this

struct queens_arg {
  int board[64]; 
  int focu开发者_运维百科s_idx;
};

called board is now being corrupted and does not reflect the original values, does anyone knows why? Thanks!

More information here:

This is the start of the function:

void *find_queens(void *args) {  

  //vars
  pthread_t thread1, thread2;
  struct queens_arg *data = (struct queens_arg *) args;
  int board[64];
  copy_array(data->board, board);
  print_board(data->board);

This is how it is called:

int board[64] = {
    0,0,0,0,0,0,0,0,
    0,0,0,0,0,0,0,0,
    0,0,0,0,0,0,0,0,
    0,0,0,0,0,0,0,0,
    0,0,0,0,0,0,0,0,
    0,0,0,0,0,0,0,0,
    0,0,0,0,0,0,0,0,
    0,0,0,0,0,0,0,0,
  };

  struct queens_arg *args = malloc(sizeof (struct queens_arg));
  args->focus_idx = 0;
  copy_array(board,args->board);
  (*find_queens)(&args);

When I print the array, I get this instead:

39456784 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0

Instead of 0 all the way. Which is weird.


I think that the problem is that what you're passing in to the function is a struct queens_arg**, not a struct queens_arg*. Notice that you're passing in a pointer to the pointer here:

(*find_queens)(&args);

When you try typecasting it here:

struct queens_arg *data = (struct queens_arg *) args;

You're converting a struct queens_arg** to a struct queens_arg*, which isn't a meaningful conversion. You'll end up reading data near the pointer as though it were a struct queens_arg, which isn't what you want.

To fix this, just pass in the args pointer by itself, rather than a pointer to the args pointer:

(*find_queens)(args);

Out of curiosity, is there a reason that you're taking in a void* instead of a struct queens_arg*? Part of the problem is that the compiler can't diagnose the nonsensical cast because you're funneling everything through void* first.


Casting a pointer to a struct to a *void and back is perfectly legal even according to the C standard, to that is unlikely to be the problem. Are you certain the pointer really starts out as a pointer to your struct queens_arg?

0

精彩评论

暂无评论...
验证码 换一张
取 消