0
#include <stdio.h>
#define IsLowerCase(c) (((c)>='a') && ((c)<='z'))
#define ToUpperCase(s) (IsLowerCase(s)? (s)-'a' + 'A': (s))

int main(void){

    char *string = "abcdefghijklmnopqrstuvwxyz";

    while(*string != '\0'){
        *string = ToUpperCase(*string);
        ++string;
    }

}

warning: ISO C++ forbids converting a string constant to 'char*' [-Wwrite-strings]

3 Answers3

1

Your char *string should be const char *string (but it is immutable); or better char string[] = .... and then declare another variable char *s = string;, and loop and step s instead of string

WWW
  • 63
  • 5
0

char *string = "abcdefghijklmnopqrstuvwxyz"; is a literal (cannot be modified), and if you try to modify it, you will be getting undefined behaviour. If you want a modifiable string, allocate memory or use a char[] array.

This will do the trick char string[] = "abcdefghijklmnopqrstuvwxyz";. Now it should work with the rest of your code.

You can get more information on your issue in this thread.

Nik
  • 1,780
  • 1
  • 14
  • 23
  • 1
    It is undefined behavior regardless of operating system, compiler, or hardware because the C Standard says so. It will cause a crash with most compiler-hardware combinations because the compiler will put the string in a read-only memory segment. – aschepler Oct 29 '17 at 17:29
0

the problem started here

char *string = "abcdefghijklmnopqrstuvwxyz";

You declared "string" as pointer to character type but initialized it with "abcdefghijklmnopqrstuvwxyz" ( this is const string and will be invalid ) . In order to correct it you need to do two things.

  1. declare a variable ,say str, of type string i.e. "string str;" and the initialize it with a string , i.e

    "string str = "abcdefghijklmnopqrstuvwxyz";
    
  2. declare your pointer "string" with type string * ,i.e string *string.

    and intialize it with the address of str, i.e

    string *string = &str;
    

    so your final code will took like this

        #include <stdio.h>
        #include<string.h> //to use the string data type
    #define IsLowerCase(c) (((c)>='a') && ((c)<='z'))
    #define ToUpperCase(s) (IsLowerCase(s)? (s)-'a' + 'A': (s))
    
    int main(void){
    string str = "abcdefghijklmnopqrstuvwxyz";
    string  *string = &str;
    while(*string != '\0'){
    *string = ToUpperCase(*string);
    ++string;
    }
    
    }
    
aditya rawat
  • 154
  • 10