I want to create a simple array of integers having 10 elements. I'm using dynamic memory to allocate a space in memory and whenever I exceed that amount It will call realloc to double its size. Whenever I type 'q' it will exit the loop and print the array.
I know my program is full of bugs, so please guide me into where I'm going wrong.
/* Simple example of dynamic memory allocation */
/* When array reaches 10 elements, it calls
realloc to double the memory space available */
#include <stdio.h>
#include <stdlib.h>
#define SIZE_ARRAY 10
int main()
{
int *a;
int length=0,i=0,ch;
a= calloc(SIZE_ARRAY, sizeof(int));
if(a == NULL)
{
printf("Not enough space. Allocation failed.\n");
exit(0);
}
printf("Fill up your array: ");
while(1)
{
scanf("%d",&ch);
if(ch == 'q') //possible mistake here
break;
a[length]=ch;
length++;
if(length % 10 == 0) //when length is 10, 20, 30 ..
{
printf("Calling realloc to double size.\n");
a=realloc(a, 2*SIZE_ARRAY*sizeof(int));
}
}
printf("You array is: \n");
for(;i<length;i++)
printf("%d ",a[i]);
return 0;
}
Whenever I type 'q' the program crashes. I'm a beginner so I know I'm doing a dumb mistake. Any help would be greatly appreciated.
a=realloc(a, 2*SIZE_ARRAY*sizeof(int));. The size there is constant. That's obviously not what you want as the size should increase for eachrealloc. Next,scanf("%d",&ch); if(ch == 'q')doesn't do what you think it does.chis being parsed as an integer. So thescanfwill always fail when you enter a non-numeric value such as'q'(always check the return value ofscanf).scanf. If the input is a valid number it will return1(the number of items parsed) otherwise it will return0(no items parsed).