views:

134

answers:

1

So, when I pass a const char * to a function once, can I use it again? It appears to end up spitting out crap to me.

const char *config_file = "file.txt";

function(int x, config_file);
cout << "Number" << x;


secondfunction(int y, config_file);

Do I need to make another pointer to config_file?

If so, how do I do that?

Thanks!

+9  A: 

No, your can use it just fine. Despite the fact that the code you gave is uncompilable, I think I understand what you're asking.

A code segment like:

const char *x = "Hello";
fnA (x);
fnB (x);

should be just fine.

If you find that fnB is not getting what it expects then either:

  • fnA is changing what x points to (normally not possible since it's a const char *); or
  • some unshown piece of code is changing the pointer itself; or
  • something is corrupting the memory.

Try this code as an example:

#include <iostream>
#include <iomanip>

static void fnA (const char *a) {
    std::cout << "fnA: [" << a << "]" << std::endl;
}
static void fnB (const char *b) {
    std::cout << "fnB: [" << b << "]" << std::endl;
}
int main (void) {
    const char *x = "Hello";
    fnA (x);
    fnB (x);
    return 0;
}

It outputs, as expected:

fnA: [Hello]
fnB: [Hello]
paxdiablo
+1 For mind reading.
karlphillip
sbi