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.)