繁体   English   中英

在 C 中测试传递给函数的字符串中第 n 个字符 == "x" 的正确方法

[英]in C the correct way to test nth character == "x" in a string passed to a function

鉴于以下情况,我遇到了分段错误,我不确定是不是因为我正在针对指针或其他问题进行测试。

测试第 4 个字符是否为逗号的正确方法是什么?

从 fifo abc,def,xyz读取字符串

char in[BUFFER] = {'\0'};
if ((in_fl = open(*fifofile, O_RDONLY)) == -1)
    {
     while (read(in_fl, in, BUFFER)>0) {
      doParseInput(&in);
    }


void *doParseInput(char *inputread){
//copy string to use later....
 char* theParsedString = calloc(strlen(inputread)+1, sizeof(char));
 strcpy(theParsedString , inputread);
 if (strcmp(theParsedString[3], ",") == 0){ //causes seg fault

我也试过直接使用传入的字符串,但也是段错误

if (strcmp(inputread[3], ",") == 0){ //causes seg fault

要将缓冲区传递给函数,请不要使用&
反而:

doParseInput(in);

比较缓冲区的第 4 个字符(索引 == 3):

if (theParsedString[3] == ','){ 

(注意单引号,意思是Character-Value ,而不是双引号,意思是"String"

首先,您将错误类型的参数传递给doParseInput 它需要一个char *但你传递给它一个char (*)[] 你的编译器应该已经警告过你了。

另一个问题是您使用字符串比较来检查单个字符。 您需要使用字符常量(即使用单引号而不是双引号)并直接将其与数组成员进行比较。

if (theParsedString[3] == ',') {

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM