Results 1 to 2 of 2
  1. #1
    Join Date
    May 2002
    Location
    MA
    Posts
    4

    Angry Unanswered: global arrays in C

    I'm trying to create an uninitialized global array in C ... does anyone know if i can do this, even? i want the user to enter the dimentions of the array in the main method so i can't just say float array[user_input]; because user_input is not yet given a value.

    does anyone know how to do this (preferably without pointers)?

    thanks a lot

  2. #2
    Join Date
    Apr 2002
    Location
    Germany
    Posts
    228
    Well, arrays in c are not really much more than a pointer to the first element of it. There is no bounds checking at all. So using arrays is actually working with pointers. You can use malloc to allocate memory for a variable size array.

    Code:
    unsigned int array_size;
    A_NICE_TYPE *myarray;
    
    /*...*/
    
    scanf("%u",&array_size);
    myarray = malloc(sizeof(A_NICE_TYPE)*array_size);
    if(myarray == NULL)
    {
        /*out of mem*/
    }
    
    /*have fun with your array*/
    
    free(myarray);
    You can access the array just like every normal array.
    myarray[0] does the same as *myarray
    and don't forget the free

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •