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);
4
  • 2
    What is not working ? What is happening ? Also, please notice that's it really resource consuming to realloc a pointer so often. Commented Apr 17, 2014 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? Commented Apr 17, 2014 at 14:17
  • 3
    Please don't cast the return value of malloc() and friends, in C. Commented Apr 17, 2014 at 14:20
  • @blue112 I dont know what is the problem. Output is some garbage values. Commented Apr 17, 2014 at 14:20

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

So! You have any other logic?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.