hello everyone...
m writin a code that will take data frm stdin from user which can b of indefinte size..
but i cant make use of static arrays....and even calloc and malloc is not working properly...what sud i do???
thanks for help...
hello everyone...
m writin a code that will take data frm stdin from user which can b of indefinte size..
but i cant make use of static arrays....and even calloc and malloc is not working properly...what sud i do???
thanks for help...
Post your code or do you think we are mind readers?
malloc() and calloc() work perfectly -- its your code that doesn't work for some unknown reason.
char *ch1,*ch2;
char ch;
ch1= (char *)malloc(1);
ch= getchar();
*ch1=ch;
while(ch!=EOF){
ch1= (char *)realloc(ch1,1);
ch1++;
ch=getchar();
*ch1=ch;
}
I don't like that your realloc'ing ch1 and then incrementing the pointer ch1. To me this seems like a recipe for disaster
Your program doesn't work because it is destroying the ch1 pointer on each loop iteration. You can't increment ch1, just leave it along after the initial allocation with malloc(). Use a different pointer or integer.
Another problem is that your program is very very slooooow -- malloc() and realloc() are rather time consuming, so instead of allocating just one character at at time you should allocate a block of characters, then when the block is filled up you should call realloc() to increase the block
#define BLOCK_SIZE 80
int block_size = 0;
int current_spot = 0;
char* c1 = 0;
char c;
while( (c = getchar()) != EOF )
{
if( block_size == current_spot)
{
c1 = realloc(c1, block_size + BLOCK_SIZE);
block_size += BLOCK_SIZE;
}
c1[current_spot] = c;
++current_spot;
}
char *ch1,*ch2;
char ch;
ch1= (char *)malloc(1);
ch= getchar();
*ch1=ch;
while(ch!=EOF){
ch1= (char *)realloc(ch1,1);
ch1++;
ch=getchar();
*ch1=ch;
}
hi,
this is ma code...for taking data from user from stdin as many line as he enters
its taking jst 5 line frm stdin then its throwing segmentation user.
ny help
thanks
In the simplest terms...Don't do this, its wrong.
ch1= (char *)realloc(ch1,1);
ch1++;
you learn to read the previous comments
thanks a lot.......its working
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.