scope question

Joined
Jan 27, 2009
Messages
2
Reaction score
0
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:
Joined
Jan 27, 2009
Messages
2
Reaction score
0
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 said:
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
 

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. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,994
Messages
2,570,223
Members
46,812
Latest member
GracielaWa

Latest Threads

Top