This is not ment to be copy paste code. I put it on this forum so you could see and examine how things are done. And i think anyway that this aint easy for understand without real example. I dont know btw is this rightway to do this but it compiles with no errors and works. A friend showed for me how to play with those pointer indexes they were pretty hard for me.
Code:
#include<stdlib.h>
#include<string.h>
#include<stdio_ext.h>/*Maybe in Linux only*/
char* user_input(){
char *ptr;
char *tmp_ptr;
int i=0;
char ch;
printf("Enter letters: (to quit enter 1)\n");
ptr=malloc(1*sizeof(char));
if(ptr==NULL){
printf("malloc() failed.\n");
return 0;
}
ptr[i]=0;
while(1){
scanf("%1c",&ch);
__fpurge(stdin); /*This is not standard, if this dont work find away to get rid of '\n'*/
if(ch=='1')
break;
tmp_ptr=realloc(ptr,i*sizeof(char)+2);
if(tmp_ptr==NULL){ /*Check if space has been allocated succesfully*/
printf("realloc() failed.\n");
return 0;
}
else
ptr=tmp_ptr; /*Enlarge the ptr memory space with allocated space if allocation ok*/
ptr[i]=ch;
ptr[i+1]='\0';
i++;
printf("Letters:%s size:%i\n",ptr,i+1);
}
return ptr;
}
int main()
{
char *p;
p=user_input();
printf("String: %s\n",p);
free(p);
return 0;
}
Tell if something is done wrong way or is there a better way to do some parts of the code.