[Solved] Convert an int** array into a char** array of a different size / composition [closed]


I think that you needed string, not 2D-Array.
You can be written out to a string like write to the standard output by implementing a string that a simple extension.

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

typedef struct char_vec {
    char *v;
    size_t capacity;
    size_t used;
} sstream;

sstream *ss_new(void);
void ss_free(sstream *ss);
void ss_putc(sstream *ss, char ch);
void ss_puts(sstream *ss, char *str);

int main(void){
    int rows = 3;
    int cols = 4;
    int **array = malloc(rows * sizeof(*array));
    for(int r = 0; r < rows; ++r){
        array[r] = malloc(cols * sizeof(**array));
    }
    //set values
    memcpy(array[0], (int[]){1,2,3,4}, cols * sizeof(**array));
    memcpy(array[1], (int[]){5,6,7,8}, cols * sizeof(**array));
    memcpy(array[2], (int[]){9,3,2,1}, cols * sizeof(**array));

    //print original array
    for(int r = 0; r < rows; ++r){
        for(int c = 0; c < cols; ++c){
            if(c)
                putchar(' ');
            printf("%d", array[r][c]);
        }
        puts("");
    }
    //make string of output
    char temp[32];
    sstream *ss = ss_new();
    ss_putc(ss, '[');
    for(int r = 0; r < rows; ++r){
        if(r)
            ss_putc(ss, ',');
        snprintf(temp, sizeof(temp), "['%d'", r + 1);//0'th index is represented as the row number
        ss_puts(ss, temp);
        for(int c = 0; c < cols; ++c){
            snprintf(temp, sizeof(temp), ",'%d'", array[r][c]);
            ss_puts(ss, temp);
        }
        ss_putc(ss, ']');
    }
    ss_putc(ss, ']');
    ss_putc(ss, '\0');

    puts(ss->v);
    ss_free(ss);

    //deallocate array
    for(int r = 0; r < rows; ++r)
        free(array[r]);
    free(array);
    return 0;
}

sstream *ss_new(void){
    sstream *ss = malloc(sizeof(*ss));
    ss->capacity = 32;
    ss->used = 0;
    ss->v = malloc(ss->capacity);
    return ss;
}
void ss_free(sstream *ss){
    free(ss->v);
    free(ss);
}

void ss_putc(sstream *ss, char ch){
    ss->v[ss->used++] = ch;
    if(ss->used == ss->capacity){
        char *temp = realloc(ss->v, ss->capacity += 32);
        if(!temp){
            ss_free(ss);
            fprintf(stderr, "fail realloc at %s\n", __func__);
            exit(EXIT_FAILURE);
        }
        ss->v = temp;
    }
}

void ss_puts(sstream *ss, char *str){
    while(*str)
        ss_putc(ss, *str++);
}

2

solved Convert an int** array into a char** array of a different size / composition [closed]