2016-08-24 46 views
-6

我試圖將看起來像下面的int **數組轉換成char **數組,行數和逗號分隔。將int **數組轉換爲不同大小/構圖的char **數組

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

的我想焦炭**陣列被表示爲將像[[ '1', '1', '2', '3', '4']的一個例子, ['2','5','6','7','8'],['3','9','3','2','1']]其中每第0個索引被表示爲行號。我不確定我能做到這一點,是否有任何已知的方法可以將int **轉換爲類似的東西?謝謝。

+2

到目前爲止請顯示您的研究/調試工作。請先閱讀[問]頁面。 –

+1

_comma seperated_ ?? – BLUEPIXY

+0

@BLUEPIXY我認爲這是char',' – noobatrilla

回答

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

[DEMO](http://ideone.com/O6oRLP) – BLUEPIXY

+0

謝謝!謝謝!與很多人說話之後,你已經看到了我的光芒。 – noobatrilla