在C中将字符设置为字符串时出错

Syn*_*ror 2 c string character segmentation-fault

嘿伙计们,我需要你的帮助.我正在尝试从字符串中提取字符并将其设置为字符串数组的第2个元素.然而像往常一样C给我分段错误,我试过sprintf,strcpy和仍然分段错误代码是:

int getwords(char *line, char *words[])
{    
    int nwords=2;  
    char *result= NULL;
    char TABS[]="\t";
    char spaces[]=" ";
    char commas[]=","; 
    result = strtok(line,TABS);
    words[1]=result[strlen(result)-1];//setting the 2nd element of the array to a char
    result[strlen(result)-1]='\0';//removing the extracted char from the string
    words[0]=result;//setting 1st element to the new modified word
    printf("the opcode is:%s and the type is:%c\n",words[0],result[strlen(result)-1]);

    return nwords;

}
Run Code Online (Sandbox Code Playgroud)

例如,如果我给它"再见".它应该返回2和一个包含2个元素的数组:1st elem ="bye"2nd elem ="." 我运行了一些测试,发现错误来自语句:words [1] = result [strlen(result)-1]; 欢迎任何帮助

pmg*_*pmg 5

你确定words是一个可修改的字符串吗?

文字字符串是不可修改的字符串.例如:这会给出分段错误:

char *test = "forty two";
test[6] = 'T'; /* make two uppercase */
Run Code Online (Sandbox Code Playgroud)

您需要显示您的调用方式getwords以及所涉及变量的定义.
我猜你正在传递指向字符串文字的指针.

  • @Arafangion:修改字符串文字实际上是未定义的行为. (2认同)