将int **数组转换为不同大小/组合的char **数组

时间:2016-08-24 06:56:36

标签: c arrays csv multidimensional-array char

我试图将类似下面的int **数组转换为由行数组成的char **数组,并以逗号分隔。

1 2 3 4
5 6 7 8
9 3 2 1

我希望将char **数组表示为[[' 1',' 1',' 2&#39]的示例;,' 3',' 4'],[' 2',' 5',' 6',& #39; 7',' 8'],[' 3',' 9',' 3',' 2',' 1']]其中每个第0个索引都表示为行号。我不确定如何实现这一点,是否有任何已知的方法可以将int **转换为类似的东西?感谢。

1 个答案:

答案 0 :(得分:0)

我认为你需要字符串,而不是2D数组 您可以通过实现一个简单扩展的字符串写出一个字符串,例如写入标准输出。

#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++);
}