#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2016
    Posts
    1
    Rep Power
    0

    Very simple code.


    Hi guys,

    I'm very new to programming in C. I have this very very simple code, that simply will not give me the wanted output..

    Code:
    int main (void)
    {
        int i, n, arraySize = 0, number = 0;
        int array[arraySize];
    
        printf ("print your wanted numbers\n");
    
        for (i = 0; i <= arraySize; i++){
            scanf("%d", &number);
            if (number == 00)
                break;
            else
                array [i] = number;
                arraySize++;
        }
        for (n = 0; n <= arraySize; n++)
            printf ("%d\n", array[n]);
    
        printf ("%d", arraySize);
        return 0;
    }
    This code gives me the output, plus an extra number, which i did not enter?? What's the mistake here?

    Thank you
    Jakob
  2. #2
  3. Contributing User
    Devshed God 1st Plane (5500 - 5999 posts)

    Join Date
    Aug 2011
    Posts
    5,792
    Rep Power
    508
    The array has space for zero items.
    filling an array of 0 elements is a bad plan. You're using memory space not assigned to your program.
    You increment arraySize which does not change the size the computer has allocated for the variable array. I recommend
    Code:
    #include<stdio.h>
    
    #define ARRAYSIZE 666
    
    int main() {
      int i, n, number = 0;
      int array[ARRAYSIZE];
    
      puts ("print your wanted numbers");
    
      for (n = 0; n < ARRAYSIZE; ++n) {
        scanf("%d", &number);
        if (! number)
          break;
        else
          array [n] = number;
      }
      for (i = 0; i < n; ++i)
        printf ("%d\n", array[i]);
    
      printf("tally: %d\n", n);
      return 0;
    }
    [code]Code tags[/code] are essential for python code and Makefiles!
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2016
    Posts
    2
    Rep Power
    0
    If your intent was to change the size of the variable array using arraySize then you should lookup malloc/free (Dynamic Memory allocation).

    There are two types of memory in C, memory on the stack (fixed/static) and memory on the heap (dynamically allocated). You need the latter for dynamic memory allocation.

    I hope this helps.

IMN logo majestic logo threadwatch logo seochat tools logo