我正在写一个基本的文本编辑器。现在,我只需要编写inrow方法,在指定的行之前添加一行。如果该行不为空,则移动下一行的字符串并添加新行。 E.g:
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;
}
感谢任何帮助。
答案 0 :(得分:0)
你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);
应该这样做:
j
您在初始化之前使用int row=24, col=24,i,j;
...
for(i=0; i<row; i++){
*(*(str+i)+j) = 0;
}
:
str
您错误地将字符串复制到*(str+4) = "cool";
:
strncpy(*(str + 4), "cool", col);
应该这样做:
rownum
没有必要在这里void dsply(int *rownum, char **str){
...
}
指点......
row
...这里也没有void inrow(int rownum, char **str, int *row){
...
}
指针......
str = realloc(str,((*row)+1));
以下行不正确:
str[rownum] = realloc(str[rownum],((*row)+1));
也许你想要的是这个:
{{1}}