I am working on a code which requires a function. This function gets a string as input and returns a string.
What I have planned so far is to get a str[], remove all $‘s and spaces, and store this in another string which is returned later:
char *getstring(char str[])
{
int i=0;
char rtn[255];
while (i<strlen(str))
{
if (str[i] != " " || str[i] != "$" )
rtn[i] = str[i];
else
rtn[i] = '';
}
return str;
}
I dont feel like this will work. Any ideas?? :-S
Problem #1:
Your function returns a pointer to a (temporary) string which is allocated on the stack. This means that once your function ends, the memory for
rtnis released, and this invalidates thechar *pointer that the function returns.What you would rather do is:
The caller to
getstringshould handle the allocation and deallocation of the string passed asrtn.Problem #2:
Your while loop will run indefinitely, because
inever increases. Puti++somewhere inside the loop.Problem #3:
The condition in your
if-statement is faulty. You comparestr[i], which is achar, to" "or"$", which are string literals (having'\0'in the end). This is wrong.You need to compare them to chars, which are indicated by apostrophes (not quotation marks).
Also, note that the test condition is wrong as well. You need a logical AND operator instead of OR.
Change the
if-statement to:Problem #4:
What does
rtn[i] = '';mean?''is an empty character constant, which is illegal in C.Did you want to just skip a character in
str?Problem #5:
You have indexation problems. Because
strandrtnmay obviously be of different length, you need to manage two running indices, one for each string.Problem #6:
rtnis not necessarily null-terminated when the function returns. Assign'\0'to the end ofrtnbefore the function returns (i.e.rtn[i] = '\0';after thewhile-loop ends).Here’s your code with all the problems mentioned above fixed:
And here’s a more efficient version that uses pointers instead of indices, and doesn’t use
strlen: