[英]Not sure why my function keeps returning an error?
Writing a function that returns the last occurrence of the character.编写返回字符最后一次出现的 function。 It returns a pointer pointing to the last matching character, or null if no match was found.它返回一个指向最后一个匹配字符的指针,如果没有找到匹配,则返回 null。
#include <stdio.h>
#include <unistd.h>
#include <string.h>
char* my_strrchr(char* a, char b) {
if(a == NULL) {
return NULL;
}
char i;
i=0;
while(a[i] != '\0') {
a[i] = b;
i = i + 1;
}
return a;
}
int main(void) {
char a[] = "abc";
char b = 'c';
printf("%s\n", my_strrchr("abc", b));
return 0;
}
Writing a function that returns the last occurrence of the character.编写返回字符最后一次出现的 function。 It returns a pointer pointing to the last matching character, or null if no match was found.它返回一个指向最后一个匹配字符的指针,如果没有找到匹配,则返回 null。
But that is not what your function my_strrchr
does.但这不是您的 function my_strrchr
所做的。 The function assigns the value in b
to each character before \0
(assuming a
needs to point to a string) and thereafter returns a pointer to the first element of the array a
is pointing to regardless of where the last occurrence of the provided character in b
in the string is: function 将b
中的值分配给\0
之前的每个字符(假设a
需要指向一个字符串),然后返回一个指向数组的第一个元素的指针a
指向,而不管提供的字符最后一次出现在哪里字符串中的b
是:
while(a[i] != '\0') {
a[i] = b;
i = i + 1;
}
return a;
What your need is more something like this:您的需要更像是这样的:
#include <stdio.h>
#include <string.h>
char* my_strrchr(char* a, char b) {
if(a == NULL) {
return NULL;
}
size_t len = strlen(a);
for(size_t i = len; i > 0; i--)
{
if(a[i-1] == b)
{
return &a[i-1];
}
}
return NULL;
}
int main(void) {
char a[] = "abc";
char b = 'c';
printf("%s\n", my_strrchr("abc", b));
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.