【问题标题】:cutting a string when a character is found找到字符时剪切字符串
【发布时间】:2019-01-07 13:29:47
【问题描述】:

我编写了一个函数,如果找到 'o',则将字符串“hello world”剪切为“hell”。

我不断收到分段错误。我不知道错误可能在哪里。 有人可以帮忙吗? 提前谢谢你。

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

char* cutString(char* str, char del){

    char *newstring =(char*) str;
    malloc(sizeof(char)*strlen(str));
    int i= 0;

    for(; newstring[i]!='\0'&&newstring[i]!=del;i++);

    if(i==strlen(newstring))
     printf("not found");
     else
     newstring[i]='\0';

    return newstring;
}


int main(){



    cutString("Hello World",'o');

    return 0;

}

【问题讨论】:

  • malloc(sizeof(char)*strlen(str));?您需要了解什么是返回值以及它们的含义。您正在使用该行代码创建一个内存块,然后将其丢弃,因为您不保存返回值。

标签: c arrays string function


【解决方案1】:

您的代码有两个主要问题:

  1. char *newstring =(char*) str 使newstring 指向旧的str。而且由于您传递了一个文字字符串(只读),您将有未定义的行为试图修改它。

  2. malloc(sizeof(char)*strlen(str)); 是内存泄漏。并且不为终结者分配空间。

崩溃可能是因为第一点,当您尝试修改只读字符串文字时。

【讨论】:

  • 所以应该是这样的char *newstring= malloc(sizeof(char)*strlen(str));
  • @momonosuke 这可能是一个好的开始,但还需要一些其他工作,因为那时内存将不包含源字符串。如前所述,如果复制整个源字符串,则终止符的空间不足。
【解决方案2】:

您的代码中存在许多问题。主要问题是您没有将返回值从malloc 分配给newstring。除此之外,您还需要malloc 一个额外的字节来终止字符串。

此外,您的循环必须将字符从 str 复制到 newstring

main 中,您必须将函数的返回值分配给一个 char 指针变量以获取新字符串。

类似:

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

char* cutString(char* str, char del){

    char *newstring = malloc(strlen(str) + 1);  // malloc into newstring
    int i= 0;

    while (newstring[i]!='\0' && str[i] != del)  // Stop when a) no more chars in str or b) "del" is found
    {
        newstring[i] = str[i];     // Copy character from str to newstring
        ++i;
    }

    newstring[i]='\0';  // Terminate the string

    return newstring;
}


int main(){
    char* newstring = cutString("Hello World",'o');  // Save the returned value
    printf("%s\", newstring);
    free(newstring);
    return 0;
}

【讨论】:

    【解决方案3】:
     newstring[i]='\0';
    

    此行无效。修改字符串文字是未定义的行为。我建议检查一下:segmentation fault when using pointer

    更好的解决方案是使用数组而不是指针

    【讨论】:

    • 问题是我必须为字符串分配新内存。那是我的作业,我读了这篇文章,我明白了为什么我的方法不正确
    猜你喜欢
    • 2021-01-08
    • 1970-01-01
    • 1970-01-01
    • 2015-08-04
    • 1970-01-01
    • 2023-03-14
    • 2011-07-26
    • 2023-03-19
    • 2022-01-21
    相关资源
    最近更新 更多