zsljulius
zsljulius

Reputation: 4103

Confusion passing string as an argument to C function

void convert(char *str){
  int i = 0;
  while (str[i]){
    if (isupper(str[i])){
      tolower(str[i]);
    }
    else if (islower(str[i])){
      toupper(str[i]);
    }
    i++;
  }
  printf(str);
}

In the function, I tried to reverse the case of each of the letters in a string. I called the function like this:

convert(input);

Where input is a type of char *. I got a segmentation fault error. What's wrong here?

Thank you!

UPDATE: My input is taken from argv[1].

  char *input;
  if (argc !=2){/* argc should be 2 for correct execution */
    /* We print argv[0] assuming it is the program name */
    printf("Please provide the string for conversion \n");
    exit(-1);
  }
  input = argv[1];

Upvotes: 2

Views: 3967

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

The reason this does not work is that you are dropping the results of toupper and tolower. You need to assign the results back to the string passed into your function:

if (isupper(str[i])){
    str[i] = tolower(str[i]);
} else if (islower(str[i])){
    str[i] = toupper(str[i]);
}

Note that in order for this to work the str must be modifiable, meaning that a call convert("Hello, World!") would be undefined behavior.

char str[] = "Hello, World!";
convert(str);
printf("%s\n", str);

Upvotes: 6

Related Questions