3
#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?

RJones
  • 85
  • 1
  • 9

2 Answers2

7
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.

digital_revenant
  • 3,274
  • 1
  • 15
  • 24
4

In addition to malloc issue,

Your loop is behaving "strangely" because the trailing newline from previous scanf is taken as new input.

So use:

int c;
while((c=getchar())!='\n' && c!=EOF) ; //to remove newlines from previous scanf

after scanf

P0W
  • 46,614
  • 9
  • 72
  • 119
  • 1
    Just Changing `scanf("%c", &mazeArrP[i][j]);` to `scanf(" %c", &mazeArrP[i][j]);` will also work. Because adding `space` before `%c` acts as `fflush();` – Vedant Terkar Oct 15 '13 at 18:18
  • I originally didn't have any prints or new lines but added them because the loop would only scan 4 characters opposed to 6. When I removed the print commands all together it still is only scanning 4 characters and incrementing strangely. – RJones Oct 15 '13 at 18:19
  • @VedantTerkar; This is one of favorite line of P0W. He used it many times here. :) – haccks Oct 15 '13 at 18:19
  • @RJones Glad that my comment was useful for you. – Vedant Terkar Oct 15 '13 at 18:26
  • @VedantTerkar Thank you to both you and P0W! – RJones Oct 15 '13 at 18:27