在 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] = {'[=11=]'};
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
我也试过直接使用传过来的字符串,但是也seg fault
if (strcmp(inputread[3], ",") == 0){ //causes seg fault
要将缓冲区传递给函数,请不要使用 &
。
相反:
doParseInput(in);
比较缓冲区的第 4 个字符(索引 == 3):
if (theParsedString[3] == ','){
(注意 single-quotes,意思是 Character-Value
,而不是 double-quotes,意思是 "String"
)
首先,您向 doParseInput
传递了错误类型的参数。它需要一个 char *
但你传递给它一个 char (*)[]
。你的编译器应该已经警告过你了。
另一个问题是您使用字符串比较来检查单个字符。您需要使用字符常量(即使用单引号而不是双引号)并将其与数组成员直接进行比较。
if (theParsedString[3] == ',') {
鉴于以下情况,我遇到了分段错误,我不确定是不是因为我正在针对指针或其他问题进行测试。
判断第 4 个字符是否为逗号的正确方法是什么?
从 fifo 读取字符串 abc,def,xyz
char in[BUFFER] = {'[=11=]'};
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
我也试过直接使用传过来的字符串,但是也seg fault
if (strcmp(inputread[3], ",") == 0){ //causes seg fault
要将缓冲区传递给函数,请不要使用 &
。
相反:
doParseInput(in);
比较缓冲区的第 4 个字符(索引 == 3):
if (theParsedString[3] == ','){
(注意 single-quotes,意思是 Character-Value
,而不是 double-quotes,意思是 "String"
)
首先,您向 doParseInput
传递了错误类型的参数。它需要一个 char *
但你传递给它一个 char (*)[]
。你的编译器应该已经警告过你了。
另一个问题是您使用字符串比较来检查单个字符。您需要使用字符常量(即使用单引号而不是双引号)并将其与数组成员直接进行比较。
if (theParsedString[3] == ',') {