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;
}

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.