0

Disclaimer: the following question is not for homework or a class assignment....just practice

I'm am trying to load an array with a file extension, based upon user input. The proper extension is present in the function, but when I print in main() to test, all I get is junk. This issue has been dogging me for a while, so I appreciate any feedback!

void choiceExt( char a[], int x  );

int main()   {
     char fileExt[7];

     choiceExt( fileExt, 4 );
     // when printed here, extension is simply junk
     cout << fileExt;

return 0;
}

void choiceExt(  char a[], int x )	{
	switch (x) {
	case 1: a = ".txt";break;
	case 2: a = ".out";break;
	case 3: a = ".in";break;
	case 4: a = ".dat";break;
	case 5: a = ".ascii";break;
	}
        // when printed here, extension is good
	cout << "ext is " << a << endl;
}
2
Contributors
1
Reply
2
Views
5 Years
Discussion Span
Last Post by Moschops
0

You are passing the function a copy of a pointer. That's what happens when you pass by value like this. A copy of the object is made, and given to the function.

The function then changes that copy (note that you're not changing what the pointer points at; you're changing the value of the pointer, that is, where in the memory the pointer is pointing). You see that this has been done with the line
cout << "ext is " << a << endl;

Then the function ends. That copy is destroyed. All that remains is the original one that has not been changed.

Edited by Moschops: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.