Reputation: 2299
I feel like this should be an easy thing to do but I keep getting segmentation fault errors. I'm trying to find the last occurrence of a character, '/' and then print one past that character.
This is mainly just for printing out a file, so that this:
directory1/directory2/hello.txt
should print out like this:
hello.txt
I'm trying to use strrchr to do this, but since it returns the last occurence of a character, It prints out this:
/hello.txt
I thought I could just advance the character pointer one past the slash, and then print that, but I get a segfault doing this:
void print_path(char *dir_name)
{
char *c_ptr = strrchr(dir_name, '/');
*c_ptr = *c_ptr + 1;
printf("%s\n", c_ptr);
}
I also looked around and tried doing a method where I copy c_ptr
to a temp variable, add one to the new temp string and then add a null character to the end, but that also caused a fault.
What should I do?
Upvotes: 0
Views: 152
Reputation: 251
The problem is with this line:
*c_ptr = *c_ptr + 1;
You're dereferencing c_ptr
. That means you're getting the value of '/' + 1
, whatever that might be. You want this instead:
void print_path(char *dir_name)
{
char *c_ptr = strrchr(dir_name, '/');
c_ptr = c_ptr + 1;
printf("%s\n", c_ptr);
}
Upvotes: 0
Reputation: 53016
You should do pointer arithmetic, this is wrong:
*c_ptr = *c_ptr + 1; // incorrect
it should be
c_ptr = c_ptr + 1;
or
c_ptr++;
or
c_ptr += 1;
in *c_ptr = *c_ptr + 1
you are dereferencing the pointer and adding to the previous value at the begening of the string, a 1
.
After strrchr
c_ptr
will point to '/'
character, i.e. *c_ptr == '/'
so
*c_ptr = *c_ptr + 1;
is equivalent to
c_ptr[0] = c_ptr[0] + 1;
i.e.
c_ptr[0] = '/' + 1;
and after that, c_ptr[0]
contains the character '0'
, so the printf()
must be printing 0hello.txt
If the substring wasn't found in the source string, strrchr()
will return NULL
, so you should check for that too.
A fixed version of your program would be
void print_path(char *dir_name)
{
char *c_ptr = strrchr(dir_name, '/');
if (c_ptr != NULL)
{
c_ptr = c_ptr + 1;
printf("%s\n", c_ptr);
}
}
Upvotes: 4