0

Can I access pointers from any function without sending info from main() to each function? I've tried looking for information but couldn't find an answer.

We Are All Monica
  • 13,000
  • 8
  • 46
  • 72
user3753834
  • 277
  • 2
  • 5
  • 11
  • As long as the function can reach the pointer, either because pointer is global or passed as function variable, then yes. – AntonH Aug 12 '14 at 19:38
  • A pointer is a variable like any other. As such, it can only be accessed from other functions if it's a global, same as any other variable. – Mooing Duck Aug 12 '14 at 19:38
  • Can you? yes. should you? no. – yamafontes Aug 12 '14 at 19:39
  • Some sample code to show what you have a hard time understanding would really help. As it is the question is way too broad for anyone to help you. Please read http://stackoverflow.com/help/dont-ask. – Asics Aug 12 '14 at 19:55
  • Depends on what you mean by "access a pointer"; are you talking about using a pointer *variable* declared within `main` or elsewhere in the program, or are you talking about accessing a memory location directly (along the lines of `char *p = 0xDEADBEEF;`)? – John Bode Aug 12 '14 at 20:44

4 Answers4

2

Did you try it?

Yes, you can, but using lots of global variables is not a good idea.

Community
  • 1
  • 1
We Are All Monica
  • 13,000
  • 8
  • 46
  • 72
0

If the pointer is passed to the function as parameter or it is declared as global then yes.

Nanc
  • 464
  • 5
  • 15
0

Yes you can, because address of variable - it's her own unique identifier in memory space, like a house address within the big city. And e.g. for debug reasons it can be very helpfull (the only thing you should be sure about - live scope of this variable, because when variable leaves her scope - pointer to this address is no longer valid).

ars
  • 707
  • 4
  • 14
0

As others have said: There are good reasons to not use many globals ("locality of code" is useful), but careful use of globals is justified in some cases. An example might help:

// A slightly contrived example to show how and when you 
// might use a global variable in a C program.
#include <stdio.h>
#include <stdlib.h>

// The following are compile-time constants, and considered
// good coding practice
#define DEBUG_WARN 1
#define DEBUG_ERROR 2

// The following is a global, accessible from any function,
// and should be used cautiously.  Note the convention (not
// universally adopted) of prefixing its name with "g_"
int g_debug_threshold = 0;

// debug_print() uses the global variable to
// decide whether or not to print a debug message.
void debug_print(char *msg, int level) {
  if (level >= g_debug_threshold) {
    fprintf(stderr, "%s\n", msg);
  }
}

void foo() {
  debug_print("hi mom", DEBUG_WARN);
}

int main(int ac, char **av) {
  // Here we set the debug threshold at runtime
  if (ac > 1) {
    g_debug_threshold = atoi(av[1]);
  }
  foo();
}
fearless_fool
  • 33,645
  • 23
  • 135
  • 217