2014-02-27 48 views
0

我正在编写一个基本的文本编辑器。现在,我只需要编写inrow方法,在指定的行之前添加一行。如果该行不为空,则移动下一行的字符串并添加新行。例如:重新分配数组的行和列

1: 
2: 
3: 
4: cool 
5: 

after run: 

1: 
2: 
3: 
4: 
5: cool 
6: 

问题是分段错误(核心转储)。我无法找到任何解决办法。

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

void inrow(int rownum, char **str, int *row); 

void main(void){ 

    int row=24, col=24,i,j; 
    char **str; int *input; char *d; 
    str =(char**) malloc(row*col); 

    for(i=0; i<row; i++) 
     *(str+i) = (char*)malloc(col); 
    for(i=0; i<row; i++){ 
    *(*(str+i)+j) = 0; 
    } 

    *(str+4) = "cool"; 
    inrow(4, str, &row); 
    dsply(&row, str); 


} 

//prints array 
void dsply(int *rownum, char **str){ 

    int i; 
    for(i=0; i<*rownum; i++) 
     printf("%d: %s\n", (i+1) ,*(str+i)); 

} 

void inrow(int rownum, char **str, int *row){ 

    char *temp; 
    str = realloc(str,((*row)+1)); 
    *temp = **(str + *row); 
    *(*(str + *row)) = 0; 
    *(str+(*row+1))= temp; 

} 

任何帮助表示赞赏。

+1

当你得到像这样的碰撞,确保程序用调试信息(GCC的'-g'标志)构建,然后在调试器中运行该程序。调试器将在发生崩溃时停止。 –

+0

另外,当你只需要96或192('24 * sizeof(char *)')字节时,你就为'str'分配了576个字节('24 * 24')。如果在解引用'str'时使用数组索引语法,它也会更容易理解(即使对你自己也是如此)。像'str [i] = malloc(...)'或'str [i] [j]'。 –

+0

该数组将展开。现在它的大小被指定为测试函数。 – Sixie

回答

0
  1. 你不当malloc荷兰国际集团记忆str

    str =(char**) malloc(row*col); 
    
    for(i=0; i<row; i++) 
        *(str+i) = (char*)malloc(col); 
    

    它应该做的事是这样的:

    str = malloc(row * sizeof(*str)); 
    for(int r = 0; r < row; r++) 
        str[r] = malloc(col); 
    
  2. 您使用j初始化之前:

    int row=24, col=24,i,j; 
    
    ... 
    
    for(i=0; i<row; i++){ 
        *(*(str+i)+j) = 0; 
    } 
    
  3. 你不当复制一个字符串str

    *(str+4) = "cool"; 
    

    它应该做的事是这样的:

    strncpy(*(str + 4), "cool", col); 
    
  4. 这是没有必要作出rownum这里的指针...

    void dsply(int *rownum, char **str){ 
        ... 
    } 
    

    ...也不row指针在这里...

    void inrow(int rownum, char **str, int *row){ 
        ... 
    } 
    
  5. 以下行不正确:

    str = realloc(str,((*row)+1)); 
    

    也许什么你打算是这样的:

    str[rownum] = realloc(str[rownum],((*row)+1)); 
    
+0

4.我用*行来改变数组的大小。 Inrow函数再添加一行,我需要访问该行。 5.随着这一点,我试图添加更多的行到二维数组的行。再次,我需要更改行号以访问最后一行。 – Sixie