Thread: Global Variables

  1. #1
    Registered User
    Join Date
    Jul 2007
    Posts
    5

    Global Variables

    Is it possible to declare global variables within a function?

    I have an array MyArray[100,total_entries] but 'total_entries' is only initialized after the application starts running and its value depends on user input. Is it possible to do this without using malloc()? Im making low-level code and malloc() isnt available for use.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    No, the only way to create some persistent memory with a variable size at run-time is to use malloc (or something like malloc).
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Oct 2001
    Posts
    2,129
    if you know how much memory you'll need ahead of time, you can declare it as static.

  4. #4
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    A two-dimensional array where one side is "variable" requires that you either "guess" the maximum of the variabl side (say, "I don't think it will ever reach 100, so let's make it 200 to be sure"), or you allocate memory using "malloc" (or friends of malloc).

    Depending on what you actually want to do, there may be several different ways to do this "best". If you give some more details of what you are actually trying to achieve, then there may be a chance that someone will also give better advice.

    --
    Mats

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 5
    Last Post: 08-06-2008, 09:59 AM
  2. scope of global variables
    By laertius in forum C++ Programming
    Replies: 4
    Last Post: 10-15-2006, 01:59 AM
  3. global variables - okay sometimes...?
    By MadHatter in forum C++ Programming
    Replies: 21
    Last Post: 01-21-2003, 04:23 PM
  4. global variables
    By rdnjr in forum Linux Programming
    Replies: 0
    Last Post: 01-07-2003, 10:28 AM
  5. Global variables? Bad! Yes, but to what extent?
    By Boksha in forum C++ Programming
    Replies: 6
    Last Post: 05-26-2002, 04:37 PM