Question: I have a C string and I'd like to shorten it, so that it gets cut from the first occurrence of '$'. Here's my code:

```
int char_search(char exp[], int s, char what) {
    int i, occurrence=-1;
    for (i=0; i < s && occurrence == -1; ++i)
        if (exp[i] == what)
            occurrence = i;

    return occurrence;
}

int shorten(char *exp, int maxlength, char *exp_new) {
    int l, i;
    l = char_search(exp, maxlength, '$');
    exp_new = (char *) malloc((l+1)*sizeof(char));
    exp_new[l] = '\0';
    for (i = 0; i<l; i++) 
        exp_new[i] = exp[i];

    return l;
}

```

The problem is it starts to overwrite the exp\_new pointer address, and only copies the first char to the actual array. Also, exp\_new returns NULL for some reason. (The string lengths might not be correct, but that shouldn't screw up the whole thing.)

Answer: 
When you want to return a pointer through a function parameter you need to use a double indirection:

```
int shorten(char *exp, int maxlength, char **exp_new)

```

A better signature would be

```
char* shorten(char *exp, int maxlength, int *length)

```

where you return the result directly.

*Edit*: When the function name "shorten" describes what it is ment to do the obvious result should be the shortened string. The length of that string resulting from the search function is a negligible result. The function could be changed so that the length parameter could accept a NULL pointer. In that case you could omitting a length result if it's not interesting for the caller. But that depends on the environment.
> 
> Also, exp\_new returns NULL for some reason. (The string lengths might not be correct, but
>  that shouldn't screw up the whole thing.)
> 
> 
> 

This is a bit worrying. You dismiss the fact that exp\_new "returns" NULL, when this is a major warning sign that something isn't right.

The last thing I would expect is that writing to a null pointer would produce useful results.

Are you describing the problem properly?

If you want to return the exp\_new to the caller you won't do it like this. You have to declare it as char \*\*, and assign the locally allocated string

```
char *local_exp_new = malloc(...) ;
*exp_new = local_exp_new ;

```