I am trying to create a function which removes C-style comments from a string.
I tried using the classic while-loop when using pointers to go through a char array, now by using two pointers(p2
is a step ahead of p1
, and they both start at the beginning). I tried checking*p1 == '/' and when *p2 == '*'
, and when it was true I'd create two new pointers which would find the end of the comment (*p3 == '*' && *p4 == '/'
), and then I'd create two new pointers p5
and p6
, the first of which would point to p1(the first character in the comment, which should be '/', and the second would point to p4(the last character which would be removed), I'd use a while loop to try and
do while(*p5++ = *p6++);
which sadly does not work.
#include <stdio.h>
void remove_comments(char* s) {
char *p1=s;
char *p2 = s;
p2++; // move p2 ahead of p1;
while(*p1 !='\0' && *p2 !='\0') {
if(*p1=='/' && *p2=='*') { // beginning of comment
char *p3 = p1; // save their positions and
char *p4 = p2; //create two new pointers
while(*p3 !='\0' && *p4 !='\0') {
if(*p3 == '*' && *p4 == '/') { //if end of comment
char *p5 = p1;
char *p6 = p4;
while(*p5++ = *p6++);
} else p1++;
p3++;
p4++;
}
}
p1++;
p2++;
}
}
int main() {
char arr[] = "This is an /*this is a comment*/ example!";
remove_comments(arr);
printf("%s", arr);
return 0;
}
The code above should produce the output This is an example!
, but the string remains unchanged. How do I fix this?
getchar()
. This question is essentially caused by a typo and hence not very interesting.s1
.