Tips and Tricks (2)

Previous T&T

For those, like myself, who come from the VB world, pointers have been a scarecrow for long and refrained the good willing volunteer from getting into the world of C… This tip deals with functions returning a string.

Say that you want to return a string from a function (returnZ) that will be passed to an other function/command, kind of:

char* returnZ() {
	char vResult[2]; // Declare vector of characters
	vResult[0] = 'Z'; // Fill in vector
	vResult[1] = '�'; // Do not forget the EOS character
	return vResult; // Return pointer to vector
}

This will not work!

The reason being that the function will in fact return a pointer to the vector of characters. And this vector, for which some memory has been allocated during execution of the function code, has been released to… I do not know, after completion of the function code.

There are a couple of turnaround solutions, among which the next exemples:

char* returnZ() {
	char static vResult[2]; // Declare static vector of characters
	vResult[0] = 'Z'; // Fill in vector
	vResult[1] = '�'; // Do not forget the EOS character
	return (vResult); // Return pointer to vector
}

In this exemple, the vector is declared as static so that it remains after the execution of the function. Draw back: some memory keeps allocated to the vector.

char* returnZ(char vResult[]) {
	vResult[0] = 'Z'; // Fill in vector
	vResult[1] = '�'; // Do not forget the EOS character
	return (vResult); // Return pointer to vector
}

In this exemple, the vector is passed to the function from the calling function/command.

Next T&T

Leave a Reply

You must be logged in to post a comment.