-2

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:

  1. The first character should be uppercase.
  2. 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.

Alureon
  • 179
  • 1
  • 3
  • 14

1 Answers1

1

To start with, having a function definition like

 void my_caller(name1) 

is problematic, as missing type (used to be, now obsolete rule) default to int. You want this to be a char *. not int.

You need to change it to

  void my_caller(char * name1) {.... 

Moreover, you need to call the function as my_caller(name1);, passing an array is the same as passing a pointer to the first element of the array.

Also, you don't pass the address of the array (check the types if you're in confusion) while calling the function.

That said, inside myFunction(), the scope of i is limited to the for loop only, but you want to use that beyond the scope (to null-terminate), so you got to declare i in the function block scope.

Moral of the story: Turn up the compiler warning / error settings, and pay close attention to the messages emitted by the compiler. They are there for a reason.


Note: After making these changes, code works as expected.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • I botched the function prototypes when I pasted them into my post. What I have is `void my_caller(*name1)`. It's not supposed to return anything, though. I just want it to print. I've edited my post. – Alureon Jan 30 '19 at 06:27
  • @WaterGuy even after your edit, you're still missing the data type. Check the code I compiled online (link in answer). – Sourav Ghosh Jan 30 '19 at 06:30
  • Damn it, I read over it too quickly. You're right, I forgot the data type. – Alureon Jan 30 '19 at 07:51