Dra*_*scu 1 c arrays pointers function cstring
有人可以解释一下为什么我会得到"分段错误......"以及如何在这段代码上修复它?
#include<stdio.h>
int str_length(char *s) {
int length = 0, i;
for(i = 0; *s; i++) {
s++;
}
return i;
}
char *strdel(char *s, int pos, int n) {
int i;
char *p, str[] = "";
p = str;
for(i = 0; i < str_length(s) - n + 1; i++) {
if(i >= pos) {
*(p + i) = *(s + i + n);
}
else {
*(p + i) = *(s + i);
}
}
s = str;
return s;
}
int main() {
char *str = "abcdef";
printf("str_lengh: %d\n", str_length(str));
printf("strdel: %s\n", strdel(str, 1, 2));
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我得到这个输出:
str_lengh: 6
strdel: adef
Segmentation fault (core dumped)
Run Code Online (Sandbox Code Playgroud)
另外,有没有更好的方法来创建一个函数:char*strdel(char*s,int pos,int n); 删除位置pos的n个字符比我做的那个?
我想你在这里写的都是...
char *strdel(char *s, int pos, int n) {
int i;
char *p, str[] = "";
p = str; // p points to str which is "" and is on the stack with length 0.
for(i = 0; i < str_length(s) - n + 1; i++) {
if(i >= pos) {
*(p + i) = *(s + i + n); // now you are writing onto the stack past p
}
else {
*(p + i) = *(s + i);// now you are writing onto the stack past p
}
}
s = str; // now s points to space on stack
return s; // now you return a pointer to the stack which is about to disapear
}
Run Code Online (Sandbox Code Playgroud)
无论何时写入过去的p,通常都会遇到未定义的行为.UB您正在写入尚未在堆上或堆栈上分配的空间.
您可以编写仅适用于s的strdel版本.如果我理解正确的strdel,那就是这样:(粗略地,未经测试!,需要检查pos和n的边界)
char *strdel(char *s, int pos, int n) {
char *dst = s + pos, *src = s + pos + n;
while(*src) {
*dst++ = *src++;
}
*dst = 0;
return s;
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1774 次 |
最近记录: |