我对c函数有错误

我对c函数有错误,c,C,我是C语言新手,我试着写代码,我需要处理字符串。我需要从字符串中剪切第一个单词,然后返回单词和字符串的其余部分 我写这段代码是为了剪切第一个单词,但是我得到了错误“分段错误(核心转储)” 有人知道为什么,怎么修吗? 符号等于“” 发布的代码包含一些问题。包括未定义的行为 警告:此代码假定参数str指向以NUL结尾的字符串 #include <stdio.h> // printf() #include <stdlib.h> // exit(), EXIT_FAILURE

我是C语言新手,我试着写代码,我需要处理字符串。我需要从字符串中剪切第一个单词,然后返回单词和字符串的其余部分

我写这段代码是为了剪切第一个单词,但是我得到了错误“分段错误(核心转储)” 有人知道为什么,怎么修吗? 符号等于“”


发布的代码包含一些问题。包括未定义的行为

警告:此代码假定参数
str
指向以NUL结尾的字符串

#include <stdio.h>  // printf()
#include <stdlib.h> // exit(), EXIT_FAILURE
#include <string.h> // strlen(), malloc()

char * cut(char *str, char *symbol)
{
    char *temp = NULL;
    if( NULL == (temp = malloc( strlen(str)+1) ) )
    { // then malloc failed
        perror( "malloc failed" );
        exit( EXIT_FAILURE );
    }

    // implied else, malloc successful

    int i;
    for(i=0; str[i] && str[i] !=symbol[0]; i++)
    {
        temp[i]=str[i];
    }

    // terminate string
    temp[i] = '\n';

    printf("temp %s\n",temp);
    return temp;
}
#包括//printf()
#包括//退出(),退出失败
#包括//strlen(),malloc()
字符*切割(字符*str,字符*符号)
{
char*temp=NULL;
如果(NULL==(temp=malloc(strlen(str)+1)))
{//然后malloc失败了
perror(“malloc失败”);
退出(退出失败);
}
//否则,malloc成功了
int i;
对于(i=0;str[i]&&str[i]!=symbol[0];i++)
{
温度[i]=str[i];
}
//终止字符串
温度[i]='\n';
printf(“临时%s\n”,临时);
返回温度;
}

然而,问题是返回第一个单词和其余的字符串,无论是张贴的代码还是我的答案都不执行,

<代码> TEMP是未初始化的指针。此外,考虑如果<代码>符号< /代码>中的字符串在<代码> STR < /代码>中会发生什么情况。你的
while
循环会发生什么情况?另外,你需要以null终止你正在复制到
temp
中的字符串…并且它不是线程安全的'cos static'。未初始化的temp是你在使用调试器时应该发现的。谢谢。这是我想要的完美工作。我试图得到第一个单词,然后我可以用与上一个答案类似的方式处理字符串的其余部分。你能告诉我这个语句是做什么的吗<代码>温度=malloc(strlen(str)+1)请阅读
malloc()
的手册页通常,malloc从
堆中分配所需的内存字节数
,并返回指向该分配内存的指针。
strlen(str)
返回字节数,在
str[]
数组中的NUL字节之前,+1要有足够的空间容纳跟踪NUL字节(NUL字节包含0x00,通常写为
'\0'
temp=
将指向已分配内存的指针分配到变量
temp
中,因此
temp
现在指向已分配内存(最终代码需要调用
free(temp)
,以避免内存泄漏
#include <stdio.h>  // printf()
#include <stdlib.h> // exit(), EXIT_FAILURE
#include <string.h> // strlen(), malloc()

char * cut(char *str, char *symbol)
{
    char *temp = NULL;
    if( NULL == (temp = malloc( strlen(str)+1) ) )
    { // then malloc failed
        perror( "malloc failed" );
        exit( EXIT_FAILURE );
    }

    // implied else, malloc successful

    int i;
    for(i=0; str[i] && str[i] !=symbol[0]; i++)
    {
        temp[i]=str[i];
    }

    // terminate string
    temp[i] = '\n';

    printf("temp %s\n",temp);
    return temp;
}