0

Here i give input string like this "/org/bluez/1509/hci0"

And i want output like this /org/bluez/1509/hci0

Here i use this method but i got Segmentation fault.

void main () 
{
    char  *str = "\"/org/bluez/1509/hci0\"";
    int len = strlen(str);
    printf("\nlength %d\n",len);
   char *str1;
   str1 = str+1;
   printf("String 1 = %s\n",str1);
   *(str1+ (strlen(str)-2)) = '\0'; 
   printf("\nString 1 = %s\n",str1);
}

I am getting output like this

length 22
String 1 = /org/bluez/1509/hci0"
Segmentation fault

Problem with Last " character.

Can Any body Help me or Suggest me new Way.?

user1089679
  • 2,328
  • 8
  • 41
  • 51
  • 1
    string literals are not modifiable. Try copying it to an array: `char str[] = "\"/org/bluez/1509/hci0\"";`. Also `main` returns an integer; change that `void`, and add a `return 0;` if you want C89 compatability (also need to declare all variables before any code statement). – pmg Jan 24 '12 at 12:33
  • I suggest changing `*(str1+ (strlen(str)-2)) = '\0';` to `str1[ strlen(str1) - 1 ] = '\0';` – Lundin Jan 24 '12 at 12:48

1 Answers1

4

Use

char str[] = "\"/org/bluez/1509/hci0\"";

Instead of a pointer. The pointer only "points" to the string literal which is not modifiable. You can read more about this in this question and a ton of other similar ones. It's even in the c-faq, take a look on it!

Community
  • 1
  • 1
sidyll
  • 57,726
  • 14
  • 108
  • 151