2012-10-22 143 views
1

我开始学习C,并希望从命令行输入字符并将它们排序为一个数组,以便行号是ASCII字符编号,列是输入字符的索引。我知道这必须通过realloc和malloc动态完成,但我不知道如何对其进行编码。有人可以帮我解决这个问题吗?Realloc二维数组

#include <stdio.h> 
#include <stdlib.h> 
#include <strings.h> 
#include <string.h> 
#include <assert.h> 
#include <ctype.h> 

#define totalASCII  256 
int 
main(int argc, char **argv) { 
int locat; 
char current; 
int **dRow=NULL; 

dRow = malloc(totalASCII*sizeof(*dRow)); 


for(locat=0;scanf("%c", &current)==1;locat++) { 
    /* I don't know what to put here */ 
    } 
return 1; 
} 
+0

** dRow是指向指针的指针而不是指向数组的指针,因此分配内存并访问它将导致分段错误 – Omkant

回答

0

您的数据太小了,真的不需要从堆中分配它。只需使用一个数组:

struct { char character; int input_index; } input_data[totalASCII]; 

在一个典型的32位系统,这将使用约256 * 8或2 KB的内存,这真的不是那么多。

然后存储将是:

for(locat = 0; scanf("%c", &current) == 1; locat++) 
{ 
    input_data[locat].character = current; 
    input_data[locat].input_index = locat; 
} 
+0

如何对列中的字符建立索引? – user1658996

+0

当多次给予同一个字符时,它将如何存储? – Rohan

+0

沿行移动到下一个空列 – user1658996

0

免责声明:没有编译和运行代码。

尝试这样:

int prev_size = 1; 

dRow = calloc(totalASCII, sizeof(*dRow)); //use calloc 

for(locat=0;scanf("%c", &current)==1;locat++) { 
    if(dRow[current]) { 
     prev_size=0; 
     //try to find how much is already allocated 
     while(dRow[current][prev_size] != -1) 
      prev_size++; 

     dRow[current] = realloc(sizeof(int) * (prev_size+1)); 
    } 
    else { 
     prev_size = 1; 
     dRow[current] = malloc(sizeof(int) * (prev_size+1)); 
    } 
    dRow[current][prev_size-1] = locat; 
    dRow[current][prev_size-1] = -1; //end identifier 

} 

的复杂性在这里是要找到以前分配的大小。由于没有其他结构/数据结构来存储此信息,因此此示例代码尝试遍历数组并找到假定为结束标记的-1