So I’m trying to do the practice exercises in K&R. It wants me to make a function similar to squeeze, I don’t get whats wrong with it. I desk checked it already. I don’t want a solution found on the net, I wanna understand why my code wont work.
//removes characters that are present in both strings
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#define MAXLTR 15
void removesame(char s1[],char s2[]);
int main(void)
{
char string1[MAXLTR],string2[MAXLTR];
printf("Enter a string: ");
scanf("\n%s",&string1);
printf("\nEnter the letters/words to be removed: ");
scanf("\n%s",&string2);
removesame(string1,string2);
printf("\nFinal output: %s",string1);
getch();
}
void removesame(char s1[],char s2[])
{
char temp[MAXLTR];
int arraycntr,comparecntr;
for(comparecntr = 0; comparecntr < MAXLTR; comparecntr++)
{
for(arraycntr = 0;arraycntr < MAXLTR;arraycntr++)
{
if(s1[arraycntr] == s2[arraycntr])
s1[arraycntr] == '\t';
}
}
comparecntr = 0;
for(arraycntr = 0; arraycntr < MAXLTR; arraycntr++)
{
if(s1[arraycntr] != '\t')
{
temp[comparecntr] = s1[arraycntr];
++comparecntr;
}
}
for(arraycntr = 0; arraycntr < MAXLTR; arraycntr++)
s1[arraycntr] = '\0';
for(arraycntr = 0;arraycntr < MAXLTR; arraycntr++)
s1[arraycntr] = temp[arraycntr];
}
This is not an assignment, but is an equality test:
you meant:
If you compile with a high warning level, the compiler may emit a message alerting you to this. The Microsoft VC compiler emits the following warning:
The initial
forloops only check ifs1ands2have the same values in the same indexes, it does not check if a char ins1exists anywhere ins2. The terminating conditions on theforloops should also be the lengths ofs1ands2, notMAXLTR:The next
forloop should usestrlen(s1)also and just assign null terminator totempafter:tempis not initialised anywhere, so contains random data, apart from that just entered during thisfor. Without a null terminator intemp,s1will end with no null terminator also (you will probably see garbage printed afterwards). Finally, juststrlen(temp) + 1when populatings1:The
+ 1will copy the null terminator tos1.Minor note, instead of calling
strlen()in the terminating condition of theforloops you can store this instead: