-4

I have a pointer array, and I want to set all values to 0.

Here is my code:

#define EMPTY 0

void initBoard(int *ptr, int n){

n = n * n;
ptr = (int*)malloc(n*sizeof(int));
int i = 0;
for(i;i<n;i++){
    *ptr = EMPTY;
    *ptr++;
}
i = 0;
for(i;i<n;i++){
    printf("%d\n",*ptr);
    *ptr++;
}

}

when running this code, I expect to get (N == 0):

0
0
0
0

instead I get this:

394066110
7321
6890384
6881472

Why am I getting this?

EDIT:

void printBoard(int *ptr){

printf("%d - %d - %d\n", ptr, ptr+1, ptr+2);
printf("%d - %d - %d\n", ptr+3, ptr+4, ptr+5);
printf("%d - %d - %d\n", ptr+6, ptr+7, ptr+8);

}

will print out:

0 - 4 - 8
12 - 16 - 20
24 - 28 - 32

here is how it looks when i call the funtion:

    int *ptr, win = 0;

initBoard(*ptr);
printBoard(*ptr);

EDIT 2:

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

//define
#define EMPTY 0
#define CROSS 1
#define CIRCLE 2
#define NO_WIN 0
#define PLAYER_WIN 1
#define COMPUTER_WIN 2
#define DRAW 3

//funktioner
void printBoard(int *ptr);
int checkWin(int *ptr);
void computerMove(int *ptr);
void initBoard(int *ptr);

int main()
{
    int *ptr, win = 0;

    initBoard(*ptr);
    printBoard(*ptr);

    return 0;
}

void printBoard(int *ptr){

    printf("%d - %d - %d\n", ptr[0], ptr[1], ptr[2]);


}

int checkWin(int *ptr){

    return 0;

}

void computerMove(int *ptr){

}

void initBoard(int *ptr){

    ptr = malloc(9*sizeof(int));
    int i = 0;
    //int *orig = ptr; //spara pointern
    for(i;i<9;i++){
        *ptr = EMPTY;
        ptr++;
    }
}
Mos Om
  • 15
  • 1
  • 4

1 Answers1

2

You misunderstand the way the dereference operator * and post-increment operator ++ interact.

When you write this *ptr++ you say "first, get me the writeable value at the pointer; then increment the pointer". This expression does not make sense by itself, because the result of dereferencing is discarded. In other words, it is equivalent to ptr++.

Now consider your second loop. Your pointer points to one past the end of the allocated block. At this point, dereferencing it is illegal.

You can fix this by storing the original pointer before coming into the first loop, and using the saved value to reset ptr before the second loop:

int i = 0;
int *orig = ptr; // Save the original pointer
for(i;i<n;i++){
    *ptr++ = EMPTY; // Combine ++ and * on assignment
}
i = 0;
ptr = orig; // Restore the original pointer
for(i;i<n;i++){
    printf("%d\n", *ptr++); // Combine ++ and * on read
}

If you would like initiBoard to initialize ptr that has not previously been set, change the signature as follows:

void initBoard(int **ptrPtr, int n);

Call initBoard(&ptr, n), and use ptrPtr with an extra level of dereference, i.e.

*ptrPtr = malloc(n*sizeof(int));
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523