c - Unable to understand scanf() behaviour in the following code -
input -
cometq hvngat
here's code -
#include <stdio.h> #include <stdlib.h> #define maxlen 6 main(void) { char comet[maxlen], group[maxlen]; unsigned long int result[2] = { 1,1 }; short int i, j; scanf("%s",comet); scanf("%s",group); printf("\ncomet's name: %s\ngroup's name: %s",comet,group); printf("\ncomet's no.: %ld\ngroup's no.: %ld",result[0],result[1]); = j = 0; while(comet[i]!='\0' && i<maxlen){ result[0] *= (comet[i] - 'a' + 1); i++; } while(group[j]!='\0' && j<maxlen){ result[1] *= (comet[j] - 'a' + 1); j++; } printf("\ncomet's no.: %ld\ngroup's no.: %ld",result[0],result[1]); printf("\ncomet's no. mod 47: %ld\ngroup's no. mod 47: %ld",result[0]%47,result[1]%47); if(result[0]%47 == result[1]%47) printf("\ngo"); else printf("\nstay"); exit(0); }
now, far know, scanf() reads string till whitespace detected. here, output is-
comet's name: cometqhvngat group's name: hvngat comet's no.: 1 group's no.: 1 comet's no.: -534663680 group's no.: 994500 comet's no. mod 47: 43 group's no. mod 47: 27 stay
but, shouldn't this?
comet = "cometq" & group = "hvngat"
i don't understand why isn't happening?
in addition, when size of comet
6 bytes, how can store - cometqhvngat
?
if want use char
array string, need null-terminate it.
in code, array length specified 6
, whereas, inputs 6
bytes, leaving no room store terminating null character. that's why, when comet
, group
passed printf()
, they're producing weird output.
a string null-terminated, , based on principle, memory access in case go beyond allocated memory size of comet
, group
, producing undefined behaviour .
safer alternative:
use fgets()
read input, limited size of buffer, rid of last \n
character, , you're good-to-go. check man page details.
also, need change format specifier %ld
%lu
unsigned long int
. %ld
used signed long int
.
Comments
Post a Comment