I'm new to C and am trying to write a simple function that can take in a string (or array of characters) and convert its case based on the following rules:
- The first character should be uppercase.
- The remaining characters should be lowercase.
I've written code, but I'm running into segmentation fault errors, and I'm baffled as to what's going wrong. Here's what I've written:
void myFunction(char name[]) {
printf("Before: %s", name);
name[0] = toupper(name[0]); // This line seems to cause problems.
// Convert the other letters to lowercase if they aren't already.
for(int i = 1; name[i] != '\0'; i++) {
if(islower(name[i])) {
name[i] = tolower(name[i]);
} else {
name[i] = name[i];
}
}
name[i] = '\0';
printf("After: %s", name);
}
void my_caller(*name1) {
printf("Name before changing case: %s\n", name1);
myFunction(name1);
printf("Name after changing case: %s\n", name1);
}
// In another .c file.
int main() {
char name1[] = "adam";
my_caller(&name1);
}
In myFunction
, if I comment out the lines except for
name[0] = toupper(name[0]);
I still get the segmentation fault. So that would suggest that this line is (one of) the culprits, but I don't understand why. I want to convert the letter to uppercase and put it back into the string.