-2

I am trying to remove a character from a string knowing its position. I am aware that there are plenty of methods, but the one I tried out produces the error in the title on line 4 of the attached code. The objective of my attempt is to make the pointer on the old character point on the next character of the string. Can someone help me understanding this issue?

char* remove_char(char str[], int pos)
{
  str = str[pos] + str;
  if (pos < strlen(str)-1)
    &(str[pos]) = &(str[pos+1]);
  else 
    str[strlen(str)-1] = 0;
  return str;
}
snus74
  • 421
  • 3
  • 9
  • 1
    You probably just need to drop the & gibberish and do `str[pos] = str[post+1];` As a rule of thumb, never program by trial and error. Tossing in random & or * until the code seems to work isn't a sensible approach. – Lundin Sep 23 '19 at 08:49
  • @Lundin this isn't random. Your solution doesn't work because it replaces the character by the next one, and you have 2 times the next character in your string. What i tried to do here is to Assign the POINTERS not their OBJECTS. – snus74 Sep 23 '19 at 08:57
  • @dandan78 thx I will look into that – snus74 Sep 23 '19 at 08:57
  • I have no idea what you are even trying to do. There are no "pointers" (plural) here, only one single pointer. `str` is an array, which when passed to the function decays into a local pointer. You can fiddle around with that pointer as much as you like, it won't affect the original array. As for taking the address of a random character, it will not result in a modifiable pointer. – Lundin Sep 23 '19 at 09:08

1 Answers1

0

This is very overcomplicated. Here is a working solution:

char* remove_char(char *str, int pos)
{
    memmove(str+pos, str+pos+1, strlen(str+pos+1) + 1);
    return str;
}

Note that I'm using memmove instead of memcpy. This is important when the buffers overlap.

In your code, the statement str = str[pos] + str; is just nonsense. Adding a pointer to a character makes no sense. For information about string concatenation, see these links:

How do I concatenate two strings in C?

How do I concatenate const/literal strings in C?

klutt
  • 30,332
  • 17
  • 55
  • 95