tags:

views:

85

answers:

6

Hi, I have a simple class Name:

   class Name
{ private:
    char nameStr[30];
  public:
    Name(const char * = "");
    char * getName() const;
    void print() const;
};

I am having two problems, which are just a bit difficult for me wrap my head around. The constructor is supposed to take an argument of const char * and copy that into the nameStr array. However, this is what I have tried and is not working:

Name::Name(const char * setName)
{
    &nameStr = setName;
}

It gives me the error "invalid lvalue in assignment". If I remove the reference in front of nameStr, it still errors, saying "incompatible types in assignment of 'const char*' to 'char[30]'". Not quite sure what I'm missing.

The other problem is the accessor method:

char * Name::getName() const
{
    return  &nameStr[0];
}

I have the same problem, it errors "invalid conversion from 'const char*' to char*'" and I can't for the life of me figure out how to make it return a pointer to a const char... I've been searching to avail. Found plenty of info on const, but can't quite figure how to apply it to my situation. Any help would be greatly appreciated!

+2  A: 

The line

char nameStr[ 30 ];

as opposed to (for example)

char * nameStr;

suggests that you want to keep a "copy" of the whole string, not just the pointer. So,

&nameStr = setName;

does not make sense. You can use something like (but may not be exactly)

strncpy( nameStr, setName, 30 );

However, on your second question, why do you want to have the getName() method return char *? I see the that the Name class is encapsulating a char array, but then if you expose the char pointer, you are breaking your own encapsulation. If you really want, you can return a const char * by return nameStr;, but better is to avoid that.

ArunSaha
memcpy is a little unsafe for something like this, and if you really wanted to use it, memcpy( nameStr, setName, 30*sizeof(char)); would be more appropriate.
KSchmidt
@KSchimdt: Fully agree. I merely continued and focussed on the question, without changing much. In reality, I would probably have `enum { N = 30 }; char nameStr[ N ];`, or even use `std::string` if available. (In work, I don't have `std` :-9)
ArunSaha
<pedantry>`sizeof(char)` == 1 by definition.</pedantry>
Whisty
It's more of a style/consistency suggestion :)
KSchmidt
Yeah, I'm supposed to be making sure not to expose the char array. It feels like I should just type const every other word and that'll cover it. I changed the return type to 'const char *' and that's what I was trying to accomplish. Thanks!
Ross Hettel
+1  A: 

When you declare something like char nameStr[30] inside a class or struct, it creates 30 contiguous characters in memory inside the class. The value of nameStr is a constant pointer to that exact position inside the class, so you can't change it. You'll have to use something like

strncpy(nanemStr, setName, 30).

This copies the contents of the string and adds a null terminator. It is limited to 30 characters so you don't overflow the buffer and destroy the universe.

JoshD
destroy the universe? Buffer overflows give a run-time error at worst.
Alexander Rafferty
@Alexander, poetic license? Security holes _can_ be pretty bad...
Whisty
Yeh, just poking fun.
Alexander Rafferty
As a note, strncpy will not null-terminate if the string being copied is at least 30 characters long. If the OP is using Visual Studio, he can use strcpy_s, or if not, it's easy to wrap strcpy with his own strcpy_s.
Jim Buck
@Alex: Writing beyond the bounds of an array is undefined behavior, which means *anything* can happen (including destruction of the universe if the computer is somehow capable of doing that).
FredOverflow
that would suck... I don't think my computer can do that though.
Alexander Rafferty
Think of it from the program's point of view. An unhandled exception is like exploding to death. (And if the debugger gets you it holds you in limbo!)
JoshD
+1  A: 

If you are open to using std::string you could do the following:

#include <string>

class Name
{ private:
    std::string nameStr;
  public:
    Name(std::string = "");
    std::string getName() const;
    void print() const;
};

Name::Name(std::string setName)
{
    nameStr = setName;
}

std::string Name::getName() const
{
    return nameStr;
}
shuttle87
The setter should take a std::string reference, so it doesn't create an unnecessary copy.
KSchmidt
... a `const` reference
ArunSaha
Thanks, but this is part of an assignment and we're using C-style strings. How I wish I could use std::string.
Ross Hettel
@ross, oh ok. I just figured I'd put the suggestion out there anyway. @KSchmidt, good point.
shuttle87
+1  A: 

I would recommend you use an std::string, but first you need to know how pointers work.

Let's take your first problem: &nameStr = setName;

Here, nameStr is an array of chars, for storing your name. &nameStr refers to the address of this array. You cannot set the address of a variable of any sort, it is illegal. For example, &a = &b (where a and b are ints) is just as illegal. Next you tried, nameStr = setName; and it said incompatible conversion from const char* to char[30]. What you are trying to do is assign one pointer to another. This doesn't actually copy the data. To copy the data, you need to do this manually, e.g.:

for (int n=0;(n>0?setName[n-1]!=0:true);n++) { nameStr[n] = setName[n]; }
// The above won't work (or might crash) if the ternary operator evaluates both sides. I don't think it does, but correct me if I'm wrong.

Note, the comparion with setName[n-1] instead of setName[n] is so the NULL character gets copied.

For your next problem, cannot convert const char* to char*. Taking the address of a variable will always yeald a constant pointer, because you are not allowed to change the address. Also note that &array[0] is essentially the same as array because you a dereferencing, then re-referencing it, thus making the process unnecessary. You need to state your getName() function as returning const char* and in it, return nameStr.

A word on arrays: Arrays are like other datatypes, except that they contain multiple of a datatype, not one. When referring to an array, its type is of a pointer to its member type. For example, an array of ints would be treated like an int*. The pointer points to it's first element. This means that using [] on an array will dereference the pointer to any of its elements.

Good luck with C++!

Alexander Rafferty
Awesome, that was tons of help, thanks! I am just starting to learn C++, and have somewhat of a grasp on pointers, but am not quite there. Thanks for the tip on arrays and being deferenced.
Ross Hettel
Oh, and how I wish I could use std::string, but this being part of an assignment, I have some limitations. Though I suppose this is a good way to be challenged.
Ross Hettel
The first time that loop runs, you will be indexing outside the bounds of setName, not a good idea... (setName[n-1] when n=0 becomes setName[-1])
KSchmidt
"Dereferencing a variable will always yeald a constant pointer" That's not accurate. The reason he's getting a const pointer is because he's declaring a statically-sized array inside a class. The pointer must always point to the data in that class (the 30 characters are in the class and contribute to its size.) But then again, maybe you meant "take the address of" rather than "dereference". And +1 for a finely detailed answer.
JoshD
yes I did... little mistake. I'll fix up the mistakes. Oh, and glad you found this helpful.
Alexander Rafferty
+1  A: 

To clarify what the error message said, the statement &nameStr = setName; literally says "Set the address of nameStr to the value stored in the variable setName". You can never change the value of a variable's address; that is a constant thing that gets assigned when the variable is defined. Because of that, &nameStr is as the compiler said, an invalid lvalue.

Bryan
A: 

First problem -

However, this is what I have tried and is not working:

Name::Name(const char * setName)
{
   &nameStr = setName;
}

It gives me the error "invalid lvalue in assignment".

Because &nameStr gives you the address of nameStr and you can't assign a value to it, it can not be used as lvalue in any of the assignment statement.

If I remove the reference in front of nameStr, it still errors, saying 
"incompatible types in assignment of 'const char*' to 'char[30]'"

Because nameStr is an array of characters and name of the array in C++ is an immutable pointer to its first element. That means you can't change the location where it points to.

Therefore, probably you should try something like this -

strcpy(nameStr, setName);

Second Problem -

char * Name::getName() const
{
    return  &nameStr[0];
}

Again, the same reason - &nameStr[0] is still equivalent to writing simply nameStr. Try changing your function signature like -

const char * Name::getName() const
Hemant