Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are these loops incrementing strangely?

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

    int main(){

        int rows, col, i, j;
        char **mazeArrP;

        scanf("%d %d", &rows, &col);

        mazeArrP = (char **) malloc(rows*sizeof(char));

        for(i = 0; i<rows; i++){

            printf("i = %d\n", i);
            mazeArrP[i] = (char *) malloc(col*sizeof(char));

            for(j = 0; j<col; j++){

                printf("j = %d\n", j);
                scanf("%c", &mazeArrP[i][j]);
            }
        }

        return 0;
    }

I used the print to identify where in the loop I currently am. I'm trying to create a simple 2D array of characters but my loops are acting oddly. This is the first time I've tried using a double pointer to create a 2D array so any help in that area is greatly appreciated as well. Its seems to be 0,0 and going to 0,1 then asking for a scan, then skipping to i=1 j =0, so on and so forth. Am i missing something fundamental here?

like image 409
RJones Avatar asked Nov 19 '25 06:11

RJones


1 Answers

mazeArrP = (char **) malloc(rows*sizeof(char));

is wrong. Change to

mazeArrP = malloc(rows * sizeof(*mazeArrP));

Also, the line

mazeArrP[i] = (char *) malloc(col*sizeof(char));

can be written as

mazeArrP[i] = malloc(col);

sizeof(char) is 1 so it is redundant.

like image 127
digital_revenant Avatar answered Nov 20 '25 21:11

digital_revenant



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!