How to convert a character (flatten) matrix to a single string in C

1 Answer

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

#define ROWS 2
#define COLS 6

char* flattenMatrix(const char mat[][COLS], int rows, int cols) {
    char* result = malloc(rows * cols + 1);  // +1 for null terminator
    if (!result) return NULL;

    int k = 0;
    for (int i = 0; i < rows; i++)
        for (int j = 0; j < cols; j++)
            result[k++] = mat[i][j];

    result[k] = '\0';
    
    return result;
}

int main() {
    const char matrix[][COLS] = {
        {'H','e','l','l','o',' '},
        {'W','o','r','l','d','!'}
    };

    char* output = flattenMatrix(matrix, ROWS, COLS);
    if (!output) return 1;

    printf("Flattened string: %s\n", output);

    free(output);
    
    return 0;
}



/*
run:

Flattened string: Hello World!

*/

 



answered Jan 10 by avibootz

Related questions

...