I am very new to C programming and am learning on my own. I want to write a code that asks user to enter some numbers and store them into an array. The program would stop if the user enters 'q'. Then it is supposed to print the array and tell the user how many numbers are in that array. (the length)
I wrote the following code, but if I leave int array[]; empty, it does't work (obviously). I can't define it either because it depends on how many numbers the user enters... I searched a lot through the Internet and came across malloc and calloc. I tried to use them here but I honestly don't know how and I'm sitting on this code for a couple of days now.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int array[]; //I want to leave this empty but C doesn't allow me to.
int len=sizeof(array)/sizeof(array[0]);
for(int a=0;a<len;a++)
{
printf("Enter element %d: ", a);
scanf("%d",&array[a]);
if(getchar()=='q')
break;
}
printf("Array: [");
for(int a=0;a<len-1;a++)
{
printf("%d, ", array[a]);
} printf("%d]", array[len]);
printf("\nArray length: %d\n", len);
return 0;
}
Sample output for int array[5];
Enter element 0: 1
Enter element 1: 2
Enter element 2: 3
Enter element 3: 4
Enter element 4: 5
Array: [1, 2, 3, 4, 5]
Array length: 5
Any help is highly appreciated. Thanks and have a nice day.