Search code examples
c++matrixcharstdio

Creating Matrix of Chars and Rotate it 180 degrees


I'm trying to input symbols (#, *, and .) into a matrix of N row and N column.

I've tried the code in this link and it does rotate the matrix but I do not know how to change the input from int to chars (symbols).

Here is my current code and it doesn't work.

    m=n; //row and columns value are the same
    printf("No of columns: %d\n", m);

    if (n>100 || m>100) //break if n or m values is more than 100
    return 0;

    printf("Enter the elements in the array:\n");
    for(i=0; i<n; i++){
        for(j=0; j<m; j++){
            scanf("%s",&A[i][j]);
        }
    }

    //store the elements in rotated matrix by iterating through all the elements in the marix 
    for(i=0; i<n; i++){
        for(j=0; j<m; j++){
            rotatedA[i][j] = A[n-i-1][m-j-1];
        }
    }

    //print out the new matrix rotated by 180 degrees
    for(i=0; i<n; i++){
        for(j=0; j<m; j++){
            printf("%s ",rotatedA[i][j]);
        }

    }


}

Here are the Input Format, Output Format, and some Input-Output Examples from my homework Formats and Examples It's an image but I'm not allowed to post image yet so I put it in a link.


Solution

  • You seem to be confusing characters and strings. You have the line

    scanf("%s",&A[i][j]);
    

    which reads a whitespace delimited string from the input, and then attempts to store it in a single character. Since the string will always have at least two characters (including the termination NUL), this will ALWAYS overrun the space for it. Mostly this will be innocuous (just overwriting A[i][j+1] etc), but if you're using the full width, it will give undefined behavior.

    What you might actually want is

    scanf(" %c", &A[i][j]);
    

    which will skip any whitespace (eg, newlines from the previous line of input) and then read a single non-whitespace character. The 'skip whitespace' behavior comes from the explicit space at the start of the format string.

    If you don't want to skip all the whitespace (want to allow space characters in your matrix, for example), you'll need to manually skip just the newlines (which you probably don't want in your matrix), but not the spaces. This could be done with a second scanf call in the inner loop

    scanf("%*[\n]");   /* discard newlines */
    scanf("%c", &A[i][j]);
    

    these two can't be combined into a single call as the first will fail (and do nothing) if there are no newlines.

    You have the same character/string confusion in your print loop, so you also need to change %s to %c there as well.