It seems you've made one big mistake, and it's in the first for loop:
for(A[i] = 0; A[i] != c; i++) {
count++;
}
Here, you're initializing A[i]
to 0. Now, let's see what's wrong with that: at that point in the code, i
is not initialized, so it has an arbitrary value (like -53451561). This is bad, because you're trying to access the -53451561th element of the array, which is never good. Of course, i
could be 0, which means that you'll get away with setting the first character of A
to 0, but the point is that you don't know the value of i
and shouldn't use it before you initialize it.
Next, this is not really how you write a for
loop, and this could very much be a mistake. What you should've written is i = 0
. This way you start from i = 0
, and use it as a counter in the loop (since the last statement in the for
loop is i++
). As a rule of thumb, the variable in the first statement of the for
is the same as the last one.
Lastly, the condition is correct, but you should account for the end of the string \0
. So, the final form of the for
loop looks something like this:
for(i = 0; A[i] != c && A[i] != '\0'; i++) {
count++;
}
Now, there's a minor issue that has been pointed out by other comments: you scanf strings without the reference &
operator:
scanf("%s", mystring);
This is because the string is already a pointer itself, so scanf
can already write the result to the pointer, without needing a pointer to the pointer.
One more thing:
You could just print the characters in the first loop, which will improve the performance of your program twice.
Finally, this is how you program could look. Please, copy this only if you understand what I've explained above:
char A[100];
char c;
int i;
scanf("%s", A);
while ((getchar()) != '\n');
scanf("%c", &c);
for(A[i] = 0; A[i] != c; i++) {
printf("%c", A[i]);
}