0

I cannot find my mistake(s), in the following piece. I assume there is something wrong with the reading, I commented out what I tried:

char **A; // pointers for the matrices
    int n, m;
    scanf("%d", &n);
    scanf("%d", &m);
    A = (char **) malloc(sizeof(char *) * n);
    if (A == NULL)
        exit(1);
    for(i=0; i < n; i++){
        A[i] = (char *)malloc(sizeof(char) * m);
        if (A[i] == NULL)
            exit(1);
    }
    for(i=0; i < n; i++){
        for(j=0; j < m; j++){
            scanf("%c", &A[i][j]);
            // A[i][j] = getchar();
            // getchar();
        }
    }
    for(i = 0; i < n; i++){
        for(j = 0; j < m; j++){
            // printf("[%d][%d]", i, j);
            printf("%c", A[i][j]);
        }
        printf("\n");
    }
NiRvanA
  • 105
  • 1
  • 1
  • 8
  • When I run this, I notice that the scanf() is catching part of the carriage return of the first couple entries. Consider https://stackoverflow.com/questions/5240789/scanf-leaves-the-new-line-char-in-the-buffer – Michael Dorgan May 11 '19 at 00:30
  • `scanf(" %c", &A[i][j]);` (note the added space) – David C. Rankin May 11 '19 at 00:41

2 Answers2

0

Don't cast the result of malloc() (and friends).

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

int main(void)
{
    int rows, cols;
    if (scanf("%d %d", &rows, &cols) != 2) {
        fputs("Input error. :(\n\n", stderr);
        return EXIT_FAILURE;
    }

    char *data = malloc(rows * cols * sizeof *data);
    if (!data) {
        fputs("Not enough memory. :(\n\n", stderr);
        return EXIT_FAILURE;
    }

    // access:
    // data[row * cols + col];

    free(data);
}
Swordfish
  • 12,971
  • 3
  • 21
  • 43
0

Consider changing this:

for(i=0; i < n; i++){
    for(j=0; j < m; j++){
        scanf("%c", &A[i][j]);

to

for(i=0; i < n; i++){
    for(j=0; j < m; j++){
        scanf(" %c", &A[i][j]);

That space will gobble up and leading spaces or newlines or whatever from the scanf() input at the start of the program.

And yes, don't cast your malloc()s as per the other answer.

Michael Dorgan
  • 12,453
  • 3
  • 31
  • 61