views:

109

answers:

2

I can't figure out what to do to make this work. Here's my code:

char* testStr = "          trim this           ";
char** pTestStr = &testStr;
trim(pTestStr);

int trim(char** pStr)
{
 char* str = *pStr;
 while(isspace(*str)) {
  (*pStr)++;
  str++;
 }

 if(*str == 0) {
  return 0;
 }

 char *end = str + strlen(str) - 1;
 while(end > str && isspace(*end))
  end--;
 *(end+1) = 0;

 return 0;
}

I get an access violation on *(end+1) = 0;, but I can't declare my testStr[] as such to avoid that, because I can't pass the pointers that way. Any ideas?

+3  A: 

You need to make testStr writeable:

char testStr[] = "          trim this           ";

The problem is that char *ptr = ... has ptr pointing to the actual literal string which is in read-only memory.

By using char testStr[] = ... you are allocating an array and having the array initialized with the same contents as the literal string. Since this is an array, it is writable.

R Samuel Klatchko
I get:cannot convert parameter 1 from 'char (*)[38]' to 'char **'
ComtriS
@user364100 - no you can't. You'll want to change your function to `char* trim(char* pStr)` and then return the pointer to the first non-whitespace character.
R Samuel Klatchko
I don't want that. I want a trim function that trims in place.
ComtriS
@user364100 - it's still doing it in place. The question is whether you modify the input parameter or return a new value.
R Samuel Klatchko
Yes, I'd like to pass a pointer to the string, and move that pointer to reflect what's been trimmed off the left.Adding the null terminator to right-trim is easy enough.
ComtriS
@user364100 - you can't change the place in memory an array references and you can't modify the contents of a literal string. You could move to the heap but that brings a different set of issues. Accept the limitations of the language and work with them.
R Samuel Klatchko
+1  A: 

Found the solution:

char testStr[] = "          trim this           ";
char* pTestStr = &testStr[0];
trim(&pTestStr);

int trim(char** pStr)
{
    if(pStr == NULL || *pStr == NULL)
        return FAILURE;
    char* str = *pStr;
    while(isspace(*str)) {
        (*pStr)++;
        str++;
    }

    if(*str == 0) {
        *pStr = str;
        return SUCCESS;
    }

    char *end = str + strlen(str) - 1;
    while(end > str && isspace(*end))
        end--;
    *(end+1) = 0;

    *pStr = str;
    return SUCCESS;
}
ComtriS