Page 1 of 1
C char[] single character removal *SOLVED*
Posted: Fri Aug 22, 2008 8:14 pm
by Troy Martin
Okay, I have a char array that I have the location of two characters that I need to remove. I tried setting them to '\0' but that didn't work. What can I do? The locations in the string are strlen(input)-6 and strlen(input)-5.
Background information: I'm implementing a line-by-line C cross-compiler for an OS (I don't think I should mention the name) and I'm using this to implement a final "\n" in puts().
Re: C char[] single character removal
Posted: Fri Aug 22, 2008 8:19 pm
by Alboin
Why not just copy the string over itself, thus overwriting the unwanted parts?
Note: '\0' indicates the end of the string. Overwriting a character with it would just prematurely end the string.
Re: C char[] single character removal
Posted: Fri Aug 22, 2008 10:58 pm
by AndrewAPrice
Out of curiosity, why are you modifying the string?
I read the source in from a stream byte-by-byte using an iterator, and if I wanted to skip over a character I just increased the iterator.
Re: C char[] single character removal
Posted: Wed Aug 27, 2008 8:54 am
by DeletedAccount
Man , use a debugger and find out what exactly is going on ... , set breakpoints etc ...
Regards
Sandeep
Re: C char[] single character removal
Posted: Wed Aug 27, 2008 9:15 am
by AJ
SandeepMathew wrote:Man , use a debugger and find out what exactly is going on ... , set breakpoints etc ...
Agree with the debugger bit (a memory dump may have helped the OP although given the original question that may be assuming too much), but out of interest
where would it help to put a breakpoint to help with this query? The OP already knows that things go wrong after replacing the characters with '\0'.
Cheers,
Adam
Re: C char[] single character removal
Posted: Thu Aug 28, 2008 2:10 am
by DeletedAccount
Hi ,
I really not know where exactly
. But i might set it where the function gets called . Also i do not have any details here .
Regards
Sandeep
Re: C char[] single character removal *SOLVED*
Posted: Fri Aug 29, 2008 6:53 pm
by B.E
I hope your checking input to make sure it's length is 6+ because 5-6=-1 and 5-5 = 0, ie buffer overflow.
if you have not solve this problem yet. give you a clue.
Code: Select all
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define STR "1234567890"
char * getstring(char * input){
char *i, *j;
int inputlen, k=0;
i = j = input;
inputlen = strlen(input);
for(;*i;k++){
*i = *j++;
if ((k == inputlen-6) || (k == inputlen-5))
continue;
i++;
}
return input;
}
int main(){
char *tmp = malloc(strlen(STR)+1);
strcpy(tmp, STR);
printf("%s\n", getstring(tmp));
return 0;
}
NOTE if code looks like crap, it's because I haven't programmed in c for a while.