开发者

storing characters in char data type C language

I can store string of few length in char data type.

But when it exceeds its capacit开发者_运维问答y what can be the alternative way to store string.

I am using char data type.

void setString(char* inPoints)
{
if (strcmp(mPoints, inPoints)!= ZERO) {

    if (mPoints) {

        free(mPoints);
    }

    mPoints = (char*)malloc((strlen(inPoints) + 1)  * sizeof(char));

    strcpy(mPoints, inPoints);
}
}


You can allocate a new, bigger array and copy the old string into it (and delete the old to prevent memory leaks), appending more characters. Or (if possible) switch to C++ string class, which makes this process easier.


realloc() should resize your string


Using strncpy instead of strcpy is normally safer, but here you alloc eachtime the right amount of memory needed to store inPoint into mPoint, so I cant see what's the point. The max length of a string you can store in mPoint is limited by the amount of malloc-able memory.

Add: you can realloc as suggested, and likely you can add a check on the length to avoid realloc-ing if the string is shorter; so mPoint would be able to hold always strings less than the longest string met so far, or equal to:


// somewhere altogether with mPoints
size_t mPointsCurrenStorage = INITVAL;
// e.g. INITVAL is 256, and you pre-malloc-ate mPoints to 256 chars
// ... in the func
size_t cl = strlen(inPoints);
if ( cl >= mPointsCurrentStorage ) {
  mPoints = realloc(mPoints, cl+1);
  mPointsCurrentStorage = cl+1;
}
strcpy(mPoints, inPoints);

this way the storage grows only...


  • strcmp with mPoints=NULL is not allowed.
  • ZERO as a constant?
  • free() accepts NULL pointers.
  • malloc() doesn't need a cast in C.
  • sizeof(char) is 1.
  • Always check the return of malloc().

Modified version:

void setString(char* inPoints)
{
    if ((mPoints == NULL) || (strcmp(mPoints, inPoints) != 0)) 
    {
        free(mPoints);

        mPoints = malloc(strlen(inPoints) + 1);

        if (mPoints != NULL)
        {
            strcpy(mPoints, inPoints);
        }
    }
}

And you're using a global variable mPoints, there are better solutions. But this and the error handling for malloc()=NULL aside, you're always allocating the needed amount, so what exactly do you mean by "exceeds its capacity"?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜