0

I'm thinking of a program which allocates memory side by side to an array while scanning it. I end up with this program and it is not working! (Surely I'm doing a BIG blunder ;) ) Need Help! Thanks in Advance!

char *arr;
int c=1,i=0;
arr=(char*)calloc(c,sizeof(char));
do
{
    arr[i]=getch();
    printf("%c",arr[i]);
    c=c+sizeof(char);
    arr=(char*)realloc(arr,c);
    i++;
}while(arr[i-1]!=13);
arr=(char*)realloc(arr,c);
arr[i]='/0';
printf("%d",sizeof(arr));
puts(arr);
free(arr);
  • 2
    What is not working ? What is happening ? Also, please notice that's it *really* resource consuming to realloc a pointer so often. – blue112 Apr 17 '14 at 14:15
  • 1
    Note that `sizeof(arr)` will print the size of `char *` (most likely 8 on your machine). Is that what you want? – someguy Apr 17 '14 at 14:17
  • 3
    [Please don't cast the return value of `malloc()` and friends, in C](http://stackoverflow.com/a/605858/28169). – unwind Apr 17 '14 at 14:20
  • @blue112 I dont know what is the problem. Output is some garbage values. – Sandeep Kaushik Apr 17 '14 at 14:20

1 Answers1

2
arr[i]='/0';

What you want is :

arr[i] = 0;

or

arr[i] = '\0';

Also, please note that it's a bad practice to reallocate memory so often. It's really CPU consuming.

What you can do, on the other hand, to have a dynamic size array, is to start with a number that fit your use (let's say, 200), and to reallocate by doubling it each time. That way, you'll do far less reallocate, and still have a adaptable size array.

char *arr;
int size = 200, i = 0;

arr = (char*) calloc(size, sizeof(char));
do
{
    arr[i] = getch();
    printf("%c", arr[i]);

    if (i + 1 > c)
    {
        c *= 2;
        arr = (char*) realloc(arr, c);
    }

    i++;
}
while(arr[i-1]!=13);

arr[i] = '\0';
printf("(%d) %s", strlen(arr), arr);
free(arr);

Also, you shouldn't cast return of malloc(), calloc() or realloc(), as stated by unwind.

Community
  • 1
  • 1
blue112
  • 52,634
  • 3
  • 45
  • 54