【问题标题】:Error when setting a character to a string in C在 C 中将字符设置为字符串时出错
【发布时间】: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


【解决方案1】:

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

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

char *test = "forty two";
test[6] = 'T'; /* make two uppercase */

您需要说明如何调用getwords 以及所涉及变量的定义。
我猜你正在传递指向字符串文字的指针。

【讨论】:

  • +1,虽然这是实现定义的,但假设它们是可修改的是不好的做法。另请注意,strtok 本身会修改该行。
  • @Arafangion:修改字符串文字实际上是未定义的行为。
  • 确实,这不是实现定义的。尝试修改文字字符串是错误的。
  • @Martin:我以为是实现定义的?
  • C99, 6.4.5p6:如果程序试图修改这样的数组,行为未定义。
【解决方案2】:

下面的代码有两个,可能是四个错误,我解释一下代码cmets中的两个错误:

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];

另外,如果“line”是静态的并且不能改变,上面的第一行会崩溃。 如果“words”没有分配或者没有引用一个至少有两个指向char的指针的数组,那么第二行就会崩溃。

如果代码执行超过这一点,任何使用“words”数组的代码都会崩溃,因为代码需要指针,但正在获取字符!

【讨论】:

  • @Aragangion:对我如何解决这个问题有什么建议吗?
  • @Syntax_Error: 那段代码有很多问题,你需要学习 C,并完全重写函数。在重写该函数时,我建议先坐下来并准确地描述该函数应该如何工作。它会返回所有单词,还是只将行分成两部分?它是否期望一个数组来存储单词?如果是这样,该阵列有多大?如果太小怎么办?如果太大了怎么办?如果函数需要分配自己的数组,它如何将它返回给调用者?
猜你喜欢
  • 1970-01-01
  • 2018-08-11
  • 2020-06-29
  • 2013-04-01
  • 2014-02-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-28
相关资源
最近更新 更多