Hi there, I'm assuming the answer to this problem is really easy, but I just can't work out where the problem is. It's driving me insane and I'd really appreciate some help. I'm new to C++.

My problem is this: I'm trying to pass a char array to a function, where a line is read from a file and then the array is passed back. However, the function returns gibberish - but ONLY when returning a file-derived array element. Here is my code:

int main ()
{
    char* tags[128];
    char* file="project3.xml";
    
    FILE *fp;
   	fp=fopen(file, "r");
   	
   	int tits = NextTag( fp, tags );
   	cout << "tags[0] post-Fn = *" << tags[0] << "*\n";
   	cout << "tags[1] post-Fn = *" << tags[1] << "*\n";
   	
	system("PAUSE");
    return 0;
}

int NextTag( FILE* fp, char* tags[] )
{
    int count2 = 0;
    char* pch;
    char rida1[512];
    fgets(rida1, sizeof(rida1), fp);
    cout << "rida1 in-Fn = *" << rida1 << "*\n";
    tags[0] = "bottoms";
    tags[1] = rida1;
    cout << "tags[0] in-Fn = *" << tags[0] << "*\n";
    cout << "tags[1] in-Fn = *" << tags[1] << "*\n";
}

The .xml file it's reading from just contains the word 'bottoms'. Here is the output:

rida1 in-Fn = *bottoms*
tags[0] in-Fn = *bottoms*
tags[1] in-Fn = *bottoms*
tags[0] post-Fn = *bottoms*
tags[1] post-Fn = *L1"*
Press any key to continue. . .

Why the gibberish on line 5 of the output when it returns the manually entered entry fine? Any ideas? It's driving me insane!!

It returns gibberish because when that NextTag() returns the array radial is destroyed, which invalidates tags[1]. What you need to do is allocate memory for the text. Then main() will have to delete[] that memory when its done with it.

tags[1] = new char[strlen(radia1)+1];
strcpy(tags[1], radia1);

Another way to do it is for main() to allocate memory for that string

char* tags[4] = {0};
char radia1[80];
tags[1] = radia1;
...
...

A-ha! I hadn't even considered that it might be because rida1 was going out of scope (I had thought that once the value of rida1 had been passed to the array then rida1's value was irrelevent).

Thanks so much - it really makes sense now!

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.