C code behaves differently as a main, as a called function -


i writing program processes users text. first wrote functions different mini-programs consisting of main-func , worked perfectly. assembling code got stuck, because 1 function behaves differently. function used input text user , place dynamically allocated memory. input ends when "end" string entered.

first was:

#include <stdio.h> #include <string.h> #include <stdlib.h>  int main() {   char** text = null;   int i,j,flag=1;   int count_strings;   char c;    for(i=0;flag;i++)   {     text = (char**)realloc(text,sizeof(char*)*(i+1));     *(text+i) = null;     c = 0;     for(j=0;c!='\n';j++)     {       c = getchar();       *(text+i) = (char*)realloc(*(text+i),sizeof(char)*(j+1));       *(*(text+i)+j) = c;     }     *(*(text+i)+j-1) = ' ';     *(*(text+i)+j) = '\0';      if(strcmp(*(text+i),"end ")==0)     {       flag = 0;       free(*(text+i));     }   }   count_strings = i-1;    for(i=0;i<count_strings;i++)   {     printf("%d.%s\n",i,*(text+i));     free(*(text+i));   }   free(text); } 

and worked this:

input: aaaa bbbb cccc dddd eeee end output: 0.aaaa  1.bbbb  2.cccc  3.dddd  4.eeee  

but when tried make callable function started behaving in different way.

char** text_input(int* count_strings) {   char** text = null;   int i,j,flag=1;   char c;    for(i=0;flag;i++)   {     text = (char**)realloc(text,sizeof(char*)*(i+1));     *(text+i) = null;     c = 0;     for(j=0;c!='\n';j++)     {       c = getchar();       *(text+i) = (char*)realloc(*(text+i),sizeof(char)*(j+1));       *(*(text+i)+j) = c;     }     *(*(text+i)+j-1) = ' ';     *(*(text+i)+j) = '\0';      if(strcmp(*(text+i),"end ")==0)     {       flag = 0;       free(*(text+i));     }   }   *count_strings = i-1;   for(i=0;i<*count_strings;i++)     printf("%d.%s\n",i,*(text+i));   return(text); } 

example:

input: aaa bbb ccc ddd eee end output: 0.  1.aaa  2.bbb  3.ccc  4.ddd  5.eee  

if code same, has changed input.

you might have had new line character in input stream before calling function. make sure previous code consumes input before proceeding.


Comments

Popular posts from this blog

javascript - ScrollTo Effect (href to div) -

javascript - ng-class not responding to change in model in Angular? -

javascript - document.registerElement extending HTMLInputElement prototype while using custom tag name to avoid implicit browser style -