char - Wrong printing in C function -
i'm writing small function in c receives char* , prints "slow motion", meaning each char after time, making typing animation.
my code is:
void funnyprint(char* string) {   int i=0;   int len=strlen(string);   if(len==0)     return;   int k=0;   char temp[1];   temp[0]=string[k];   for(i=0; i<7142800*len; i++)   {       fflush(stdout);     if((i!=0) && (i%7142800==0))     {       printf(temp);       k++;       if(k<len)            temp[0]=string[k];     }   } }   now, problem doesn't print string, , gives partly char* , partly gibberish instead.
i figured out problem memory, tried copying "string" new char*, called "new". got code:
void funnyprint(char* string) {   int i=0;   int len=strlen(string);   if(len==0)     return;   int k=0;   char temp[1];   char * new=malloc(len*sizeof(char));   strncpy(new,string,len);   temp[0]=new[k];   for(i=0; i<7142800*len; i++)   {       fflush(stdout);     if((i!=0) && (i%7142800==0))     {       printf(temp);       k++;       if(k<len)            temp[0]=new[k];     }   } }   yet result did not change. i'm feeling i'm missing small issue here, happy if can enlighten me.
thanks!
printf(temp);   your temp array not null-terminated, hence weird(aka undefined) behavior. don't see need of char array here. should single char.
char temp = string[k];   and later
printf("%c", temp);      
Comments
Post a Comment