在C中将字符设置为字符串时出错
嘿,伙计们,我需要你们的帮助。我试图从字符串中提取一个字符,并将其设置为字符串数组的第二个元素。然而,像往常一样,C给了我分段错误,我尝试了sprintf、strcpy,仍然是分段错误代码是:在C中将字符设置为字符串时出错,c,string,segmentation-fault,character,C,String,Segmentation Fault,Character,嘿,伙计们,我需要你们的帮助。我试图从字符串中提取一个字符,并将其设置为字符串数组的第二个元素。然而,像往常一样,C给了我分段错误,我尝试了sprintf、strcpy,仍然是分段错误代码是: int getwords(char *line, char *words[]) { int nwords=2; char *result= NULL; char TABS[]="\t"; char spaces[]=" "; char commas[]=
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;
}
e、 g.如果我给它“bye”,它应该返回2和一个包含2个元素的数组:1st elem=“bye”2nd elem=“”
我运行了一些测试,发现错误来自以下语句:
单词[1]=结果[strlen(result)-1];
任何帮助都是welcom您确定
words
是可修改的字符串吗
文字字符串是不可修改的字符串。例如:这会产生分段错误:
char *test = "forty two";
test[6] = 'T'; /* make two uppercase */
您需要显示如何调用getwords
以及相关变量的定义。我猜您正在向字符串文本传递指针。下面的代码中有两个,也许是四个错误,我解释了代码注释中的两个错误:
If we assume that "line", for the purposes of explaining what happens, is "hey\tthere"...
We also assume that "words" is an array of two pointers to char.
// Find the first token, in this case "hey", and return it in "result".
result = strtok(line,TABS); // NOTE: 'line' has been modified by the function!
// Take the last character in the returned statement, which is 'y', and
// copy it to the second cell in the 'words' array, however we are supposed
// to be copying a *pointer* to char there...
words[1]=result[strlen(result)-1];
此外,如果“行”是静态的且无法更改,则上面的第一行将崩溃。
如果未分配“words”或未引用至少包含两个指向char的指针的数组,则第二行将崩溃
如果代码执行超过这一点,任何使用“words”数组的代码都将崩溃,因为代码需要指针,但得到的是字符 +1,虽然这是实现定义的,但假设它们是可修改的是不好的做法。还要注意,strtok本身将修改该行。@Arafangion:修改字符串文字实际上是未定义的行为。实际上,这不是实现定义的。试图修改文字字符串是一个错误。@马丁:我以为它是实现定义的?C99,6.4.5p6:如果程序试图修改这样的数组,则行为是未定义的。这看起来像是PHP而不是C。这里有多个错误
result
不是数组。@mingos:指针可以像数组一样被索引<代码>指针[索引]与*(指针+索引)
完全相同。确认,我的坏!谢谢您的更正,我把strtok误认为strcspn,它返回一个大小。对不起,请忽略我最初的评论。/几乎/完全一样。。。sizeof运算符将具有不同的行为。:)@Aragangion:有没有关于我如何解决这个问题的建议?@Syntax\u Error:这段代码有太多错误,你需要学习C语言,并完全重写函数。在重写该函数时,我建议首先坐下来,确切地描述该函数应该如何工作。它是返回所有单词,还是只将行一分为二?它是否需要一个数组来存储单词?如果是,那么这个阵列有多大?如果太小怎么办?如果太大怎么办?如果函数需要分配自己的数组,它将如何将其返回给调用方?