new char[x], how to use it?

I made an attempt at defining a pointer:
char *usrspell = 0;
Then I tried to make a new char with the length of input, called difference, and I did this:
[code]
if (!(usrspell=new char[difference])) {
cout << "Memory allocation failed";
exit(10);
};
[/code]

But when I go to retrieve *usrspell, I only get the first character, and when I retrieve usrspell, I get the memory data with the characters I'm putting in to it at the beginning and a bunch of junk on the end, which is kind of hard to run checks on. How do I get only the part with letters or how do I fix it so *usrspell isn't one character?

(I'm using new because some of the names might be kind of long, while others may be really short, and I didn't want an extra 40 characters on the end.)

Comments

  • The allocating routine is fine.

    How did you put that input in that string the pointer points at? Jus try it with strcpy ... otherwise you have to add some '' at the end of it, so you don't get some beeps and funny chars on your screen by calling for example: cout << mypointersname.

    pointers on strings are handled different than normal pointers, just the pointers name without a "*" will give you access to the whole string, but never forget the '' which marks the end of some string.
    best regards,

    sebastian mohrenstecher
    executive secretary
    net::allies

    www.net-allies.de
    info@net-allies.de

  • you are not using the new because of... i didnt understand your explanation. you are using new because you are using c++.
    and for the same reason you should use string instead of char*.


    : I made an attempt at defining a pointer:
    : char *usrspell = 0;
    : Then I tried to make a new char with the length of input, called difference, and I did this:
    : [code]
    : if (!(usrspell=new char[difference])) {
    : cout << "Memory allocation failed";
    : exit(10);
    : };
    : [/code]
    :
    : But when I go to retrieve *usrspell, I only get the first character, and when I retrieve usrspell, I get the memory data with the characters I'm putting in to it at the beginning and a bunch of junk on the end, which is kind of hard to run checks on. How do I get only the part with letters or how do I fix it so *usrspell isn't one character?
    :
    : (I'm using new because some of the names might be kind of long, while others may be really short, and I didn't want an extra 40 characters on the end.)
    :

Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories