Here is my code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
|
#include <cstdio>
struct A {
const char *name;
void setName (const char *n) {
name = n;
}
};
void Assign (A *a) {
char string[256] = "test"; // <------------
a->setName(string);
}
int main () {
A *a;
a = new A();
Assign(a);
printf("%s", a->name);
return 0;
}
|
Currently, running this code will output nothing.
If I change the line signified by "<---------" to
or
|
const char *string = "test";
|
it outputs "test".
If I change the line to
or
it outputs junk.
If I don't use declare "a" as a pointer, and instead as an object (passing its address in to Assign()), it outputs "test".
If I copy the code inside the Assign() function and paste it where I call Assign(), it outputs "test".
I think I might sort of have a feeling of what is happening, but I wouldn't be able to explain it if I tried.
Could someone tell me what the problem is? Don't tell me how to fix it (unless you know a different way that might be useful), because I obviously already know how to fix it. I just want to know what is going on.
Just so you know, the project I ran into this problem on is making it hard to fix this. I need to be able to change each character individually in "string" before passing it into "a". That can't be done with "char *" (I think?), so I need to use "char [256]", but I ran into this.