-
pointer arithmetic
Ok. so I'm writing up the below assignment and have a little snag in the code
• takes command line arguments of one string and two single characters
• locates the first character in the string: if the character was located at position i, then the character at position (i+2) of the string is changed to be the second input character. This operation is repeated until all the sought character occurrences have been found and changed.
For example, here would be some sample runs of the program:
/home/you> lab13q1 gbc g Y
Modified string is: gbY
/home/you> lab13q1 "abc deaf hiaklar" a X
Modified string is: abX deafXhiakXar
the "abc deaf hjaklar" doesn't work propery cause it's trying to read after the string has ended. I tried putting if statement that will print "wtf" once reaches null but it's not working. I'm justt getting 3 XXX at the end of the 2nd example. How do I correct it? Thanks.
Code:
#include <stdio.h>
#include <string.h>
int main (int argc, char *argv[]) {
char *str = argv[1], value1 = *argv[2], value2 = *argv[3], *temp;
temp = str;
while ((temp = strchr(temp, value1)) != NULL) {
if ((temp + 2) != NULL) {
*(temp + 2) = value2;
temp++;
}
else
printf ("wtf");
}
-
You also need
char *end = str + strlen(str);
Then your if statement becomes
if ( (temp+2) < end )
At that point, you know you're still within bounds of the string, and you can change a character.
-
Ok. cool...that looks like a better way of doing....for my learning curve though, do you know why what I didn't doesn't work?
-
Well it's like picking any random integer (say 1234) and then trying to write
if ( 1234 + 2 != 0 )
-
What do you think about:
Code:
#include <stdio.h>
#include <string.h>
int main (int argc, char *argv[]) {
char *str = argv[1], value1 = *argv[2], value2 = *argv[3], *temp;
temp = str;
while ((temp = strchr(temp, value1)) != NULL) {
if ( strlen(temp)>2 )
temp[2] = value2;
temp++;
}
-
I think you have a very odd way of doing whatever it is you think you are doing.
Quzah.
-
Odd? You don't know what you say.
-
Put it this way, if you have a string 1K long full of comma separated values (probably a couple of hundred), you're going to be calling strlen() an awful lot of times (with results that count down steadily from 1000).
In my example, a pointer to the end is already calculated, so all there is is a simple comparison.
-
I took salem's advise and got it working perfectly
Code:
char *end = str + strlen(str);
while ((temp = strchr(temp, value1)) != NULL && (temp +2) < end)
Now, another part of questions asks to write to stderr....I can write the function and works fine but totally don't get the point of it. Can someone explain why I would use it? Why wouldn't i just use printf without using stderr. Also, can i retrieve the error message from stderr? Good Quality links to read about stderr would be sufficient, if they are for C.
thanks a million