我试图转换一个int**数组,看起来像下面,成一个字符**数组,由行数组成,并以逗号分隔。
1 2 3 4
5 6 7 8
9 3 2 1
我希望char**数组表示为[['1','1','2','3','4'],['2','5','6','7','8'],['3','9','3','2','1']]的示例,其中每个第0个索引表示为行号。我真的不确定如何才能实现这一点,是否有任何已知的方法可以很好地将int**转换成这样的东西?谢谢。
我认为你需要的是字符串,而不是2D-Array。
通过实现一个简单扩展的字符串,可以像写入标准输出一样写入字符串。
#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, ' ');
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 %sn", __func__);
exit(EXIT_FAILURE);
}
ss->v = temp;
}
}
void ss_puts(sstream *ss, char *str){
while(*str)
ss_putc(ss, *str++);
}