I have a header file which contains a member variable declaration of a static char array:
class ABC
{
public:
static char newArray[4];
// other variables / functions
private:
void setArray(int i, char * ptr);
}
In the CPP file, I have the array initialized to NULL:
char ABC::newArray[4] = {0};
In the ABC constructor, I need to overwrite this value with a value constructed at runtime, such as the encoding of an integer:
ABC::ABC()
{
int i; //some int value defined at runtime
memset(newArray, 0, 4); // not sure if this is necessary
setArray(i,newArray);
}
...
void setArray(int i, char * value)
{
// encoding i to set value[0] ... value [3]
}
When I return from this function, and print the modified newArray value, it prints out many more characters than the 4 specified in the array declaration.
Any ideas why this is the case.
I just want to set the char array to 4 characters and nothing further.
Thanks…
How are you printing it? In C++ (and C), strings are terminated with a nul. (
\0). If you’re doing something like:It’s going to print “uhoh” along with anything else it runs across until it gets to a
\0. You might want to do something like:(Having a
statictied to instances of a class doesn’t really make sense, by the way. Also, you can just do= {}, though it’s not needed sincestaticvariables are zero-initialized anyway. Lastly, no it doesn’t make sense tomemsetsomething then rewrite the contents anyway.)