[英]I am trying to implent my own strpbrk function in C
function 應該與 C 中的strpbrk
function 類似地工作。 當我運行代碼時,出現分段錯誤。 我做了一個橡皮鴨調試,但無法找出代碼的任何問題。 我在 WSL 上使用 gcc 編譯器。 main.h header 文件包含 function 聲明char *_strpbrk(char *s, char *accept)
。 請問我錯過了什么?
#include "main.h"
/**
* _strpbrk - searches the string s for any of a set of bytes
*
* @s: String to be searched
* @accept: Substring of bytes to search for
* Return: Return a pointer to the byte in s that matches one of the bytes in
* accept, or NULL if no such byte is found
*/
char *_strpbrk(char *s, char *accept)
{
int i, j, check = 0, position = 0;
i = 0;
while (*(s + i) != '\0')
{
for (j = 0; *(accept + j) != '\0'; j++) /* Check if character of s in focus is a character in accept. Break out of the for loop if true*/
{
if (*(s + i) == *(accept + j))
{
check = 1;
position = i;
break;
}
}
if (check == 1) /* check if the character of s in focus was found to be in accept. Break out of the while loop if true */
{
break;
}
i++;
}
if (position == 0) /* Check for return value. Return null if whole string traversed*/
{
return ('\0');
}
else
{
return (s + position);
}
}
忘了提到gcc
標志-Wall -pedantic -Werror -Wextra -std=gnu89
在編譯期間使用。
_
作為前綴。char *mystrchr(const char *str, const char c)
{
while(*str)
{
if(*str == c) return (char *)str;
str++;
}
return NULL;
}
char *mystrbrk(const char *str, const char *brk)
{
while(*str)
{
if(mystrchr(brk, *str)) return (char *)str;
str++;
}
return NULL;
}
現在你的代碼:
return ('\0');
這不是返回指針。 你很幸運,因為'\0'
將轉換為指針 NULL。 基本上,當你想太多事情時,很難分析。
#include "main.h"
/**
* _strpbrk - searches the string s for any of a set of bytes
*
* @s: String to be searched
* @accept: Substring of bytes to search for
* Return: Return a pointer to the byte in s that matches one of the bytes in
* accept, or NULL if no such byte is found
*/
char *_strpbrk(char *s, char *accept)
{
int i, j, check = 0, position = 0;
i = 0;
while (*(s + i) != '\0')
{
for (j = 0; *(accept + j) != '\0'; j++) /* Check if character of s in focus is a character in accept. Break out of the for loop if true*/
{
if (*(s + i) == *(accept + j))
{
check = 1;
position = i;
break;
}
}
if (check == 1) /* check if the character of s in focus was found to be in accept. Break out of the while loop if true */
{
break;
}
i++;
}
if (position == 0) /* Check for return value. Return null if whole string traversed*/
{
return ('\0');
}
else
{
return (s + position);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.