Rein Van Imschoot
Rein Van Imschoot

Reputation: 344

Difficulties when replacing char in string in C using pointers

I'm working my way through C Programming: A Modern Approach but I'm having a bit of trouble with the last exercise of the chapter on strings.

I'm trying to replace a character in a string with a null character to remove the file_name but I keep getting a bus error and I don't understand what I am doing wrong:

void remove_filename(char *url)
{
  char *last_slash;

  while (*url++)
    if (*url == '/')
      last_slash = url;

  *last_slash = '\0';
}

The way I see it, I am keeping track of the address of the last slash (in the last_slash pointer). Then I target the object stored at that address and replace it by a null character.

Any feedback as to why my reasoning is false is greatly appreciated!

Upvotes: 0

Views: 148

Answers (1)

Oka
Oka

Reputation: 26345

Initialize last_slash so that you can properly check if a '/' was found after the loop. Restructure the loop to only move the pointer after first checking the value it points to.

#include <stdio.h>

void remove_filename(char *url)
{
  char *last_slash = NULL;

  for (; *url; url++)
      if (*url == '/')
          last_slash = url;

  if (last_slash)
      *last_slash = '\0';
}

int main(void)
{
    char buffer[] = "path/to/some/file.data";

    printf("<<%s>> -> ", buffer);
    remove_filename(buffer);
    printf("<<%s>>\n", buffer);
}

Output:

<<path/to/some/file.data>> -> <<path/to/some>>

Upvotes: 1

Related Questions