Reputation: 21
I get some strange result with strrchr. please help me.
Here is my code:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
char szString[32] = "hello-world-and-everyone";
char* ptemp = NULL;
ptemp = strrchr(szString, '-');
if (ptemp == NULL)
{
printf("Invalid string\n");
return 1;
}
printf("%s\n", szString);
printf("%s\n", ptemp );
*ptemp = 0;
printf("%s\n", szString);
return 0;
}
Expected result:
hello-world-and-everyone
-everyone
hello-world-and-everyone
Acutal result:
hello-world-and-everyone
-everyone
hello-world-and
Upvotes: 2
Views: 235
Reputation: 76908
strrchr
returns a pointer to the last occurrence of -
in szString
.
Here:
*ptemp = 0;
You set the value it points at to 0
(NULL
), replacing the -
. So when you print szString
it now ends there because strings are terminated using 0
.
Change it to:
*ptemp = 65; // ASCII 'A'
And your output would be:
hello-world-and-everyone
-everyone
hello-world-andAeveryone
Upvotes: 3
Reputation: 726779
The actual results are correct (which should come as no surprise, really).
The first two lines of output agree with your expectations, so I assume that you understand them well. Here is what's happening in the last two lines: the first line (the assignment) null-terminates the szString
at the position of the last dash:
*ptemp = 0; // Replaces the last dash '-' with '\0'
so the string becomes
h e l l o - w o r l d - a n d \0 e v e r y o n e \0
When you print it now, printf
finds the first terminator, and stops there. That is why you see the truncated string in the output, rather than the original one.
Upvotes: 4
Reputation: 308364
Strings in C are zero terminated, meaning a character with a value of 0 marks the end of the string. When you did *ptemp = 0
you inserted such a character at the start of the found string, which is now the end of the original string.
Perhaps you meant to null the pointer instead by doing ptemp = 0
(no *
)?
Upvotes: 1
Reputation: 58274
strrchr
doesn't allocate and copy into a new string. It returns a pointer into the existing string where the given character is. So, when you did this:
*ptemp = 0;
You set the character at that location in your original string to NULL (0). and ended up with:
hello-world-and
Upvotes: 1