scope question

Discussion in 'C Programming' started by ktwalker, Jan 27, 2009.

  1. ktwalker

    ktwalker

    Joined:
    Jan 27, 2009
    Messages:
    2
    Likes Received:
    0
    Location:
    san diego, ca
    Hello folks,

    I have two questions.

    - can one declare several pointers in main(), pass these pointers as arguments to a function, point these pointers to malloc'd memory inside this function, and still access this memory in main() after the function returns? An initial experiment suggested that this is illegal, which I interpret to mean that declaration of a pointer and the memory allocated for that pointer each have individual scopes that are not necessarily the same.

    - can one define a pointer to an array "above main", then allocate the memory for it in a function that is called from within main() and still have the memory be accessible to main after the function returns? I suspect based on what I interpreted from the above experiment that the answer is no.

    LATER EDIT:
    - If a pointer to an array is declared above main and malloc'd at the top of main, is the memory assigned to the array visible within all functions that are called later from within main?

    Many thanks,
    kris
     
    Last edited: Jan 27, 2009
    ktwalker, Jan 27, 2009
    #1
    1. Advertisements

  2. ktwalker

    ktwalker

    Joined:
    Jan 27, 2009
    Messages:
    2
    Likes Received:
    0
    Location:
    san diego, ca
    So some example programs I just wrote suggest that answers to my questions are NO, YES, and YES. If I am wrong and my example programs failed to show a memory violation, please let me know.

    Thanks for looking,
    kris

     
    ktwalker, Jan 27, 2009
    #2
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.