How to convert a matrix of numbers to a string in C

1 Answer

0 votes
#include <stdio.h>
#include <string.h>

#define ROWS 5
#define COLS 6

void matrixToString(int rows, int cols, int matrix[rows][cols], char *result) {
    char buffer[16]; // Temporary buffer for each number
    result[0] = '\0'; // Initialize the result string

    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            snprintf(buffer, sizeof(buffer), "%d", matrix[i][j]); // Convert number to string
            strcat(result, buffer); // Append to result string
            if (j < cols - 1) {
                strcat(result, " "); // Add space between numbers
            }
        }
        if (i < rows - 1) {
            strcat(result, "\n"); // Add newline between rows
        }
    }
}

int main() {
    int matrix[ROWS][COLS] = {
        {4, 7, 9, 18, 29, 0},
        {1, 9, 18, 99, 4, 3},
        {9, 17, 89, 2, 7, 5},
        {19, 49, 6, 1, 9, 8},
        {29, 4, 7, 9, 18, 6}
    };

    char result[512]; // Ensure this is large enough to hold the entire string
    
    matrixToString(ROWS, COLS, matrix, result);

    printf("Matrix as string:\n%s\n", result);
    
    return 0;
}



/*
run:

Matrix as string:
4 7 9 18 29 0
1 9 18 99 4 3
9 17 89 2 7 5
19 49 6 1 9 8
29 4 7 9 18 6

*/

 



answered May 24, 2025 by avibootz
...