Hey everyone:
Can someone tell me why when I called printf in main I get a blank character. I ran this code in a C interpreter and it works fine, but when I compile with gcc and run it, it doesn't print out the new string. I get a empty string.
I've included the functions that are being called.
Thanks for the help.
int main() {
char *test = "This is a test 12345";
char *test2 = splitString(test);
printf(test2);
}
char* splitString(char* string) {
char *letterString = NULL;
char *numberString = NULL;
char *newString = NULL;
int stringSize = strlen(string);
newString = malloc(sizeof(char) * stringSize);
if(newString == NULL) {
printf("Memory couldnt be allocated");
}
letterString = findLettersAndPunctuation(string);
numberString = findNumbers(string);
strcat(newString, numberString);
strcat(newString, letterString);
printf(newString);
//newString = strcat(numberString,letterString);
free(letterString);
free(numberString);
return newString;
}
char* findLettersAndPunctuation(char* string) {
char *letterString = NULL;
int stringLength = strlen(string);
int loopCounter = 0;
int letterStringCounter = 0;
letterString = malloc(sizeof(char) * (stringLength));
if(letterString == NULL) {
printf("Memory Could Not be allocated");
exit(1);
}
for(loopCounter; loopCounter <= stringLength; loopCounter++) {
if(isalpha(string[loopCounter]) == 1 || ispunct(string[loopCounter]) == 1
|| isspace(string[loopCounter]) == 1) {
letterString[letterStringCounter] = string[loopCounter];
letterStringCounter++;
}
}
letterString[letterStringCounter] = '\0';
return letterString;
}
char* findNumbers(char* string) {
char *numberString = NULL;
int stringLength = strlen(string);
int loopCounter = 0;
int numberStringCounter = 0;
numberString = malloc(sizeof(char) * stringLength);
if(numberString == NULL) {
printf("Memory Could Not be allocated");
exit(1);
}
for(loopCounter; loopCounter <= stringLength; loopCounter++) {
if(isdigit(string[loopCounter]) == 1) {
numberString[numberStringCounter] = string[loopCounter];
numberStringCounter++;
}
}
numberString[numberStringCounter] = ' ';
numberString[numberStringCounter + 1] = '\0';
return numberString;
}