Hello. I'm new to C, and trying to figure out why some code I wrote isn't working. The code is supposed to receive a telephone number that could be formatted with digits, parenths, or dashes. It is supposed to strip out the parenths and dashes, retaining just the digits. Here's the code:
Even though the calling function is passing a properly validated string, this function returns an empty string. Can someone help me figure out what's going on?
I know there are other ways of accomplishing the desired result but I am curious about why this isn't working. Thanks for your help!
Code:
char* formatNum (char* validNum) {
int counter;
int index;
int length;
char* numOut;
char validChar;
counter = 0;
index = 0;
length = strlen (validNum);
numOut = malloc ((length + 1) * sizeof(char));
while (counter <= length) {
validChar = validNum[counter];
if (validChar != '-' && validChar !='(' && validChar != ')') {
numOut[index] = validChar;
index++;
} // end if
counter++;
} // end while
numOut[index] = '\0';
return numOut;
} // end formatNum
I know there are other ways of accomplishing the desired result but I am curious about why this isn't working. Thanks for your help!
Comment