From: "hymanho" <[EMAIL PROTECTED]>
Subject: About the string variable

> when I use the CW debugger, I saw that not all CharPtr
> variable was not null when I declare it. but that will let my
> program make wrong. In order to get string variable with
> null initialzation, so I use MemHandleNew() and
> MemHandleLock(), sometimes it seem ok, but it was not
> stable, it is also possibily to get a not null string variable,
> so can you please tell me why? and give me the right
> routine to declare and initialize a string variable?

There are two general methods to declare and initialize a string variable:

Method #1
-----------
Char msg1[23];
StrCopy(msg1, "This is the 1st string");

Method #2
-----------
MemHandle msgH;
Char *msg2;
// allocate space for the string
msgH = MemHandleNew( 23 );
if (msgH)
{
    msg2 = (Char *)MemHandleLock( msgH );
    if (msg2)
    {
        // now you can initialize msg2...
        StrCopy(msg2, "This is the 2nd string");
        // unlock msgH so it can be moved around in memory
        MemHandleUnlock(msgH);
    }
    // free the memory when totally done with it
    MemHandleFree(msgH);
}

In method #1, the life of the string is determined by the scope within which
it is declared.  In method #2, you free up the space used by the string
whenever you are done with it.

I'm not sure what you mean when you say you want the strings to be
initialized to NULL.  Do you want to make the string empty, or do you want
the pointer to the string to be NULL?  If you want the string itself to be
empty, use one of the following:

Char msg1[23] = "";
StrCopy(msg1, "");
...
StrCopy(msg2, "");

If you want the pointer to be NULL, that is not possible for msg1 since
declaring it to be an array of 23 Chars sets aside 23 bytes of memory
somewhere and points msg1 to that memory.  If you want to set msg2 to NULL,
you can use one of the following:

Char * msg2 = NULL;
msg2 = NULL;

but don't set it to NULL after you have allocated memory for the string
without first freeing that memory.

If any of the above points seem confusing, I'd suggest you get a book on C.




-- 
For information on using the Palm Developer Forums, or to unsubscribe, please see 
http://www.palmos.com/dev/tech/support/forums/

Reply via email to