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...

Recommended Answers

All 3 Replies

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

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

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.

commented: Very good point. +7
commented: well spotted +27
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.