Followers 0

# problems with memset

## 7 posts in this topic

Here's the code:

class gg{
public:
char ce[10];
gg(char j = ' ') { memset(ce,j,sizeof(ce));};
};
int main() {
gg x('m');
cout << x.ce << endl;

}


It outputs all those 10 ms,and then a series of weird symbols appear,why does that happen?

0

Thank a lot

0

##### Share on other sites

perhaps the easiest thing to do is:

char ce[10];       // declare string

ce[0]=0;             // set string to ""

0

##### Share on other sites

Note: this only works since sizeof char is defined as 1.

You can solve this by using sizeof(char):

memset(ce, j, sizeof(ce) - sizeof(char));

However, unless I'm very mistaken, sizeof(char) is guaranteed to be 1.

1

##### Share on other sites

Note: this only works since sizeof char is defined as 1.

You can solve this by using sizeof(char):

memset(ce, j, sizeof(ce) - sizeof(char));

However, unless I'm very mistaken, sizeof(char) is guaranteed to be 1.

Only if the char array is previously initialized to zero, which I believe is not the case for local variables (their value, and, for pointers, the memory they point to, is undefined).

EDIT: never mind that. And, yes, sizeof(char) is defined to be 1 by the C and C++ standard. Don't have the references with me now, though. Of course it's best to get in the habit of using vectors (and strings) if using C++, there's no overhead and it's just simpler and safer to use, not to mention more idiomatic.

Edited by Bacterius
0

##### Share on other sites

Yeah I know, that's why I said it was DEFINED as 1 ;)

0

## Create an account

Register a new account