本文介绍了C字符串指针函数strdel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

能否有人请解释我为什么得到分段错......,以及如何解决它此位code的?

Can someone please explain me why I get "Segmentation fault..." and how to fix it on this bit of code?

#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;
}

和我得到这样的输出:

str_lengh: 6
strdel: adef
Segmentation fault (core dumped)

此外,有没有更好的方法来创建一个函数:
    字符* strdel(字符* S,诠释POS,INT N);
从一个比我做?

Also, is there a better way to create a function: char *strdel(char *s, int pos, int n);that deletes the n characters from position pos than the one I did?

推荐答案

我觉得你写遍堆在这里...

I think you are writing all over the stack here...

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 
}

当你写过去的P,这往往是,你正在运行到未定义的行为。 UB
你正在编写成没有被分配在堆或栈上的空间。

Whenever you write past p, which is often, you are running into Undefined Behavior. UBYou are writing into space which has not been allocated on the heap or on the stack.

您可以编写一个版本strdel的是只适用于秒。像这样的东西,如果我理解正确的strdel:(大致,没有测试过!需要在边界检查POS机和N)

You can write a version of strdel that works only on s. Something like this if I understand strdel right: (roughly, not tested!, needs bounds checking on pos and 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;
}

这篇关于C字符串指针函数strdel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-16 23:49