-1

I want to capitalize the first letter of the string "hello stackoverflow". In my C program, this string is stored in a char pointer named str_to_capitalize.

I don't understand why the following code is flowless :

#include <stdio.h>

void main()
{
    char *str_to_capitalize = "hello stackoverflow";
    printf("Value pointed by str_to_capitalize : %c\n", *str_to_capitalize);
    //output: Value pointed by str_to_capitalize : h
}

but this one throw a segfault :

#include <stdio.h>

void main()
{
    char *str_to_capitalize = "hello stackoverflow";
    // printf("Value pointed by str_to_capitalize : %c\n", *str_to_capitalize);
    *str_to_capitalize -= 32; //segfault
}
  • 4
    modifying a string literal is undefined behavior. Change that to `char str_to_capitalize[] = ...`: https://stackoverflow.com/questions/58584310/why-can-i-not-modify-a-string-literal-in-c – yano May 24 '22 at 16:49
  • It's not obligated to put the bytes for the constant string literal into memory that is writable. – Wyck May 24 '22 at 16:50
  • Use an *array* instead: `char str_to_capitalize[] = "hello stackoverflow";` – Some programmer dude May 24 '22 at 16:51
  • Also, what resource are you using to learn C? What does it say about literal strings? – Some programmer dude May 24 '22 at 16:51
  • And don't use [*magic numbers*](https://en.wikipedia.org/wiki/Magic_number_(programming)). Use [the standard character manipulation functions](https://en.cppreference.com/w/c/string/byte#Character_manipulation) like [`toupper`](https://en.cppreference.com/w/c/string/byte/toupper). – Some programmer dude May 24 '22 at 16:53
  • @Some programmer dude Im trying to learn by myself, i wasn't aware of the notion of string literal ! ... For the sake of my exercice, i was not able to use toupper or any library – treuleuleu May 24 '22 at 16:55
  • If you're not allowed to use any standard C functions, then be careful: C doesn't specify any character encoding! There are character encodings where that will not work. Think Unicode and [UTF-8](https://en.wikipedia.org/wiki/UTF-8), or many older (but still in some production environments) encodings like [EBCDIC](https://en.wikipedia.org/wiki/EBCDIC). – Some programmer dude May 24 '22 at 17:00

0 Answers0