Hello guys,
I would like to ask you if anybody knows how to fix or upgrade my function "set". My teacher wrote me that I have to allocate the function inside not in main. And second thing is how to change that the pointers to pointers in function would be simplified.
Thanks for help
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFFER_SIZE 128
int set(char *in, char **out);
int main(int argc, char **argv)
{
char inStr[BUFFER_SIZE] = { 0 };
char *outStr = NULL;
int changed = 0;
printf("Exercise 10.1\n");
printf("Enter string:");
if (!fgets(inStr, BUFFER_SIZE, stdin)) { //enter string
printf("Error load string...\n");
exit(EXIT_FAILURE);
}
int lenght = strlen(inStr); //include '\n' char as last
inStr[lenght - 1] = '\0'; //remove last char '\n' from fgets function
outStr = (char *) malloc(lenght); //alloc new string of lenght
if (!outStr) {
printf("Error in alloc memory...\n");
exit(EXIT_FAILURE);
}
changed = set(inStr, &outStr); //call function
printf("Original string: %s\n", inStr);
printf("Changed string: %s and changed letters: %d\n", outStr, changed);
free(outStr); //free alloc memory
getchar();
return 0;
}
int set(char *in, char **out)
{
char *tmpString = *out; //temp variable, out cannot be used like out++
int changed = 0; //changed letters
while (*in) {
if (*in >= 65 && *in <= 90) {
*tmpString = *in + 32;
changed++;
} else if (*in >= 97 && *in <= 122) {
*tmpString = *in - 32;
changed++;
} else {
*tmpString = *in;
}
in++;
tmpString++;
}
*tmpString = '\0'; //add ending char '\0'
return changed;
}