user3299912
user3299912

Reputation: 7

using malloc() with 2d array, not getting expected results

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 ()

Upvotes: 0

Views: 67

Answers (1)

congusbongus
congusbongus

Reputation: 14622

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.

Upvotes: 1

Related Questions