[C language] Input and output a string into a two-dimensional array

Asked 2 years ago, Updated 2 years ago, 84 views

I'm trying to enter a string in a two-dimensional array, but it doesn't work

If the name of the two-dimensional array is matrix, is it correct that each character in the string is in matrix[i][j]?

For example, if you assign "str" to matrix[1], matrix[1][0] becomes s...? I wrote the following code on the assumption that this would work.

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

#define maxcount 1000000;

int main() {

    int row, column, count = 0;

    scanf_s("%d %d", &row, &column);

        // Memory allocation part
    char** matrix = (char**)malloc(sizeof(char*)*row);
    for (int i = 0; i < row; i++)
        matrix[i] = (char*)malloc(sizeof(char)*column);

    printf("%d\n", matrix[0][0]); // output for testing

        // Enter a string in a two-dimensional array matrix[i]
    for (int i = 0; i < row; i++) {
        scanf_s(" %s", matrix[i], sizeof(char)*column);
        printf("%c\n", matrix[i][0]); // output for testing
    }

    printf("%s", matrix[1]); // output for testing

        // Value Output
    for (int i = 0; i < row; i++) {
        printf("\n");
        for (int j = 0; j < column; j++)
            printf("%c ", matrix[i][j]);
    }
}

Input value

2 2

ab

ab

The output value for is

 ?

 ?

Here's the one.

The string wasn't typed properly. I don't know what the problem is ㅠ<

C6385 'matrix' is reading invalid data. Readable size is 'sizeof(char *)*row' bytes, but in reality only '8' bytes can be read.

I see this error, but I don't know the cause of it either. What's the problem?

2d-array string pointer memory-allocation

2022-09-22 18:05

1 Answers

If you use scanf_s, I think you're working in a visual studio environment.

For this, hang a breakpoint and run a line by the debugger in debug mode to see how the values of the variables change and how the memory changes.

Taking this opportunity to learn how to use a debugger will be much more helpful in your life than anyone else will tell you the answer. Visual Studio Debugger is so friendly and easy to use, it won't be too difficult.


2022-09-22 18:05

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.