【发布时间】:2011-05-27 13:28:57
【问题描述】:
大家好,我需要你的帮助。我正在尝试从字符串中提取一个字符并将其设置为字符串数组的第二个元素。然而,像往常一样,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;
}
例如如果我给它“再见”。它应该返回 2 和一个包含 2 个元素的数组: 1st elem="bye" 2nd elem="." 我进行了一些测试,发现错误来自以下语句: 词[1]=结果[strlen(结果)-1]; 欢迎任何帮助
【问题讨论】:
-
这看起来像 PHP 而不是 C。这里有多个错误。
result不是数组。 -
@mingos:指针可以完全作为数组进行索引。
pointer[index]与*(pointer+index)完全相同。 -
哎呀,我的错!感谢您的更正,我把
strtok误认为strcspn,它返回一个size_t。对不起,请忽略我的第一句话。 -
/almost/ 与数组完全一样... sizeof 运算符会有不同的行为。 :)
标签: c string segmentation-fault character