Sunday, July 12, 2009

C++ problem?

I wrote this program, it does successfully compile but when running it hangs. and i think the prob must be something like wrong use of function.





#include %26lt;stdio.h%26gt;


#include %26lt;iostream%26gt;





void sp_to_dash(char *str);


char s;


int main(void){


printf("Please Enter a expression: \n");


scanf("%c",s);


sp_to_dash("s");


system("pause");


}


void sp_to_dash(char *str){


while (*str)


{


if (*str==' ') printf("%c",'_');


else printf("%c",*str);


str++;


}


}

C++ problem?
sp_to_dash("s");





You are passing the literal value string "S" to the function, BTW... probably not your intention. try sp_to_dash(s).





also, you really don't have anything to terminate your loop. Especially when sending in a literal. The program will just happily keep skipping through memory until it randomly and accidentally runs into a NULL somewhere.





You need to fix the parameter pass as well as add code to make sure that your input string is ALWAYS null terminated...or else check for the str = length of str also in your loop control.
Reply:"s" is defined as a single character, so when you go into the sp_to_dash() routine, you send the address of "s". then you do something then increment the pointer. the problem is the next address location is just garbage because you are only dealing with 1 character. also the line" while(*str) seems to me to be an infinite loop.
Reply:while (*str)





This condition may never be false if str is not null-terminated.
Reply:Why are you passing "s" to your function? Shouldn't you be passing your string you just got from scanf?


No comments:

Post a Comment