Sandeep Kaushik
Sandeep Kaushik

Reputation: 31

Allocating memory to an array Automatically

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);

Upvotes: 0

Views: 41

Answers (1)

blue112
blue112

Reputation: 56442

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.

Upvotes: 2

Related Questions