954,504 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Question about the following code.

const char *getName() 
	{ return name; }


Looking at the following code which is a member function of a class, why would one pass the array of a person's name as a pointer and lock it so it cannot be modified when they can just pass a copy that won't affect the original? Is it because it takes less CPU?

Thanks for the help...

rosenberg_a
Newbie Poster
17 posts since Jan 2009
Reputation Points: 48
Solved Threads: 0
 

You might want to try something like this, but yes it uses more CPU and memory.

#define YOUR_ARRAY_SIZE 256
#include <string.h>

char * getName(){
    char buf[YOUR_ARRAY_SIZE];
    sprintf(buf,name);
    return &buf[0];
}
venomxxl
Junior Poster in Training
72 posts since Jan 2009
Reputation Points: 34
Solved Threads: 7
 

Yes, it's more efficient to just pass the pointer.

It adds security if that pointer is const. Thus, user of the class cannot modify the array member - preventing array overruns.

If it's needed to be able to modify the name without using any class members, then the user can copy that name to an array or string they allocated, and be able to safely modify that.

Consider the string type. This code results in a compiler error

string s = "Hello, World";
s.c_str( )[0] = 'h';

While this would work

string s = "Hello, World";
char str[100];
strcpy( str, s.c_str( ) );
str[0] = 'h';
vmanes
Posting Virtuoso
1,914 posts since Aug 2007
Reputation Points: 1,268
Solved Threads: 228
 

Please be VERY CAREFUL with this code.

Consider

// THIS IS VERY VERY WRONG!!!!
char * getName(){
    char buf[YOUR_ARRAY_SIZE];
    sprintf(buf,name);
    return &buf[0];
}


The code above is a runtime error, the problem is the you have a local variable (buf) and that goes out of scope at the end of the function. BUT you are passing the pointer to that memory, which you expect to use!!! It is possible/likely that sometime later the program will use that space for something else. Then you will have corrupted the string you are looking at, or even worst you might actually change it!!!!

The orginal is correct, if you want a copy (to manipulate) then make a local copy out of the methods. If you want to change a buffer in the class use a class method.

Sorry for the rant but this kind of error, is normally (a) Very difficult to debug, (b) dormant for a long while so it ends up in customers code.

StuXYZ
Practically a Master Poster
680 posts since Nov 2008
Reputation Points: 760
Solved Threads: 138
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You