0

Program takes a malloc'd char * from another function into a malloc'd heigth x width grid. I can't help but think it's the way I'm filling the grid that's faulty. For debugging I've added the print of the ongoing operation. When compared with the same loop right after it, the results are different (results after the code). I don't understand why my allocated memory looks like it's been altered right after.

Ive looked at this for so long now my mind's going blank.

void fill_grid ( char **g, FILE *file_in, int *w, int *h )
{


char *temp_row;
for( int i = 0 ; i < *h ; ++i ){
    (read_next(&temp_row, file_in));
    for( int j = 0 ; j < *w ; ++j ){
        (*g)[i * *h + j] = (temp_row)[j];
        printf("%c", (*g)[i * *h + j]);
    }
    printf("\n");
}

printf("WHYYYY IS THIS :\n");
for( int i = 0 ; i < *h ; ++i ){
    for( int j = 0 ; j < *w ; ++j ){
        printf("%c", (*g)[i * *h + j]);
    }
    printf("\n");
}
free(temp_row);

In the main()

char *grid;
grid = malloc(sizeof(char)*grid_w*grid_h);
fill_grid( &grid, file_grid, &grid_w, &grid_h );

Results in shell, the first "grid" is exactly as read in the .txt file, the second I assume would be the state of my allocated memory (split in half and weird) :

123456789999
123456789999
111111111999
123456789999
222222222999
123456789999
WHYYYY:
123456123456
123456111111
111111123456
123456222222
222222123456
123456789999

I hope someone can make sense of this and point out what I'm obviously missing out on. Thanks.

edit : superfluous ()

1
  • 1
    Perhaps this helps (not likely, but maybe). If your 2D backdrop is supposed to represent ar[W][H] the proper 1D backdrop for any [i][j] pairing is [i*W + j]. You appear to be using [i*H + j].
    – WhozCraig
    Commented Feb 12, 2014 at 3:54

1 Answer 1

1

Replace

(*g)[i * *h + j]

with

(*g)[i * *w + j]

Your 2d array (w wide by h height) has a "stride" of w; that is, to go to the next row, you need to advance by exactly w elements.

2
  • Thanks, I knew it was something dumb... I feel stupid and somewhat enlighted. Commented Feb 12, 2014 at 4:02
  • @user3299912 you're welcome; experienced programmers have all felt the same way countless times - a mix of "aha!" and "d'oh!" Commented Feb 12, 2014 at 4:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.