How can I declare an array with an undefined size in C?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • YuriZahard
    New Member
    • Oct 2014
    • 1

    How can I declare an array with an undefined size in C?

    I've been trying to figure this out for hours. I need to make a program that will let the user input values and it will only stop accepting once the user has inputted a negative number then it will display its mode and frequency.

    The problem is I can't find a way to let the user input values freely without asking first for the no. of values he will enter. Please help.



    Code:
    #include<stdio.h>
    
    int main()
    {
    int i,j,k=1,p,a[20],b[20],n,cnt=1,big;
    clrscr();
    printf("Enter the number of elements:\n");
    scanf("%d",&n);
    printf("Enter the numbers: ");
    for(i=1; i<=n; i++)
    scanf("%d",&a[i]);
    for(i=1; i<=n; i++)
    {
    for(j=i+1;j<=n; j++)
    {
    if(a[i]==a[j])
    cnt++;
    }
    b[k]=cnt;
    k++;
    cnt=1;
    }
    
    big=b[1];
    p=1;
    for(i=2; i<=n; i++)
    {
    if(big<b[i])
    {
    big=b[i];
    p=i;
    }
    }
    printf("\nThe mode is %d and it has occurred %d times.\n",a[p],b[p]);
    getch();
    }
  • donbock
    Recognized Expert Top Contributor
    • Mar 2008
    • 2427

    #2
    You can dynamically size the array by using malloc for the initial allocation and realloc to increase the allocation as needed. Don't forget to call free when you're done. You can take advantage of the fact that a pointer to a buffer of N items can be used as if it were an array of N items.

    Comment

    • weaknessforcats
      Recognized Expert Expert
      • Mar 2007
      • 9214

      #3
      You might also consider using malloc initially to allocate enough memory for some reasonable number of values, say 5 or 10. Then if no negative number appears you can realloc for another 5 or 10 values. realloc is expensive and you should not do it after every value entered.

      I agree you should never ask the user for the number of values. Knowing the number of values is hard on the user but easy on the programmer. Just backwards. Everything should be easy for the user. If that's hard on the programmer, it's jut too bad:)

      Comment

      Working...