-9

This is what I'm trying to do but my code is either not compiling or giving me an unexpected output "BC" instead of just "B".

#include <stdio.h>

void removeFirstAndLastChar(char** string) {
    *string += 1; // Removes the first character
    int i = 0;
    for (; *string[i] != '\0'; i++);
    *string[i - 1] = '\0';
}

int main(void) {
    char* title = "ABC";
    removeFirstAndLastChar(&title);
    printf("%s", title);
    // Expected output: B
    return 0;
}

I looked through a lot of answers here related to passing pointers by reference but none of them seemed to contain the operations that I want to do in my removeFirstAndLastChar() function.

hb20007
  • 515
  • 1
  • 9
  • 23

1 Answers1

2

I do not judge your algorithm or C conventions, friends who comment on your problem are totally right. But if you still do it in this way you can use this approach.

#include <stdio.h>
#include <string.h>

void removeFirstAndLastChar(char* string) {
    memmove(string,string+1,strlen(string));
    string[strlen(string)-1]=0;
}

int main(void) {
    char title[] = "ABC";
    removeFirstAndLastChar(title);
    printf("%s", title);
    // Expected output: B
    return 0;
}
ffguven
  • 187
  • 11