Reputation: 23
I am writing a program to count the occurrence of '2' followed by '1' in a sting. I dynamically allocated string
Code is:
#include <stdio.h>
#include<stdlib.h>
int penalty_shoot(char* s){
int count=0,i=0;
while(s[i]!='\0'){
if(s[i]=='2')
if(s[i+1]=='1')
count++;
i++;
}
return count;
}
int main() {
int t;
int i=0;
scanf("%d",&t); //t is for number of test cases.
while(t--){
char *str, c;
str = (char*)malloc(1*sizeof(char));
while(c = getc(stdin),c!='\n')
{
str[i] = c;
i++;
str=realloc(str,i*sizeof(char));
}
str[i] ='\0';
printf("%s\n",str);
printf("%d\n",penalty_shoot(str));
free(str);
str=NULL;
i=0;
}
return 0;
}
Input is :
3
101201212110
10101
2120
I am facing 2 problems:
1) I feel the dynamic allocation is not working fine.I wrote the code for dynamic allocation seeing various codes on stackoverflow . (Can anyone suggest some changes.)
2) The code isn't reading '2120' as the 3rd input. (why is it so ?)
Upvotes: 0
Views: 97
Reputation: 1031
Three errors:
Not checking for EOF
:
Change while(c = getc(stdin),c!='\n')
to while(c=getc(stdin),c!='\n'&&c!=EOF)
Reallocating with the wrong number of bytes:
Change str=realloc(str,i*sizeof(char));
to str=realloc(str,(i+1)*sizeof(char));
After taking one character input we increment i
(i++
), so the next character will be stored at the ith
position. Now, in order to store the character at ith
position, the length of the character array must be i+1
. So, we realloc
with i+1
.
Just for the sake of brevity, as suggested by Basile, you might as well do this:
Change
str=realloc(str,(i+1)*sizeof(char));
tostr=realloc(str,i+1);
Why? Because
sizeof char
is1
byte
Not consuming the \n
after inputting t
:
Change scanf("%d",&t);
to scanf("%d ",&t);
or scanf("%d\n",&t);
scanf("%d ",&t);
or scanf("%d\n",&t);
.
Either of them works. Why, you ask? Read this explanation taken from another SO answer here:
An
\n
- or any whitespace character - in the format string consumes an entire (possibly empty) sequence of whitespace characters in the input. So the scanf only returns when it encounters the next non-whitespace character, or the end of the input stream.
Tested here.
Upvotes: 2
Reputation: 480
you can use scanf("%d ", &t);
when user input to test
then just before second while loop, which condition should be c != '\n'
write c = getchar();
and then make sure you create a char variable, i called mine clear, that receives 0 so when you loop after initiating your string you write c = clear;
and under it c = getchar()
again. and when you use realloc make sure you make it bigger by (i+1) since char is only the size of 1 byte.
we create the clear variable in order to clear the buffer.
it worked for me. make sure you insert the string all at once.
Upvotes: 0