1

I am trying to make a code which changes the letter in the character array.

Most of the codes are working well. However, when I try to change capital letters into small letters(or vice versa), the code doesn't work and the program ends.

I presume it is because the pointer cannot use itself or similar reason. But I can't point out the right reason.

I am worried if it is xy question, but please understand I don't want to upload the whole question since it is my assignment and I want to solve the problem by my self as much as I can, and I think it is the right way to learn program.

#include <stdio.h>
#include <string.h>
int main(void){
    //initialize
    char *ae = "sample";
    // for (){}
    ae[0] -= 36;//at this point, program stops
    // tried ae[0] = ae[0] -36 ; *ae = *ae - 36; and so on...
    printf("%c", ae[0] - 36);
}

Thank you for your time:)

anastaciu
  • 23,467
  • 7
  • 28
  • 53
Jaeho Song
  • 63
  • 1
  • 10

1 Answers1

0

This expression...

char *ae = "sample";

...initializes the pointer with a string literal, these are read-only and can't be modified. The expression ae[0] -= 36; attempts to change the first character of this string literal, but this is not allowed and causes undefined behavior.

Instead, use:

char ae[] = "sample";

In another note, subtracting 36 from an alphabetic character does not convert it to its upper case, at least not in ASCII encoding, you might have meant 32.

Anyway, this is not very portable, you can use toupper() and tolower() from <ctype.h> library for a more robust option.

anastaciu
  • 23,467
  • 7
  • 28
  • 53