global arrays ???

This is a discussion on global arrays ??? within the C Programming forums, part of the General Programming Boards category; help! i'm trying to declare a global array in C but don't know how to. i want it to be ...

  1. #1
    Unregistered
    Guest

    Unhappy global arrays ???

    help! i'm trying to declare a global array in C but don't know how to. i want it to be uninitialized and have the user input the dimention later (and THEN initialize it) ... is this possible? do i HAVE to use pointers? :-\

    thanks.

  2. #2
    ....
    Join Date
    Aug 2001
    Location
    Groningen (NL)
    Posts
    2,386
    >i'm trying to declare a global array in C but don't know how to.

    Declare the array outside of any function. Then it is global to all functions in the file and can also be used by functions in other files.

    >have the user input the dimention later

    So you want a dynamically created array. Yes, then you will need pointers. Just declare a global variable like:

    int *dynamic_array;

    Which is a pointer to int. With malloc() you can allocate a block of ints. Like:

    dynamic_array = malloc (sizeof (int) * array_size);

    And don't forget to free the memory when you don't use the memory anymore or before exiting the program.

    free (dynamic_array);

  3. #3
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,796
    >do i HAVE to use pointers?
    If the user is going to define the size of the array at run-time, then you must use pointers and dynamic memory allocation to simulate a dynamic array. As it is, you seem to want something like this:
    Code:
    #include <stdlib.h>
    
    int *globalArray;
    
    int main ( void )
    {
      int size;
      puts ( "Enter the number of elements in the array" );
      scanf ( "%d", &size );
      globalArray = malloc ( size * sizeof *globalArray );
      if ( globalArray != NULL ) {
        /* All is well, work with the new array */
        free ( globalArray );
      }
      else {
        /* malloc failed, try again or abort */
      }
      return EXIT_SUCCESS;
    }
    -Prelude
    My best code is written with the delete key.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Global arrays shared between multiple source files
    By mike_g in forum C Programming
    Replies: 4
    Last Post: 08-14-2008, 07:29 PM
  2. Dyanmic Arrays - Global?
    By Greatgraddage in forum C Programming
    Replies: 14
    Last Post: 01-09-2007, 08:58 AM
  3. global variables and multidimensional arrays
    By LowLife in forum C Programming
    Replies: 12
    Last Post: 11-18-2005, 04:02 PM
  4. OOP and global arrays
    By dan20n in forum C++ Programming
    Replies: 3
    Last Post: 02-25-2005, 12:10 AM
  5. How to declare global arrays of unknown length?
    By ajm218 in forum C Programming
    Replies: 3
    Last Post: 08-07-2003, 10:13 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21