0

I've written something similar to this code for my answer to pset2 Substitution. The idea is to keep string s the same, but have a variable s_capital that converts s into uppercase. I can't work out why it's returning a segmentation fault after hours of searching around. Some help would be very appreciated :)

#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <ctype.h>

int main(void)
{
    string s = "hello";
    string s_capital = s;
    for (int i = 0; i < strlen(s); i++)
    {
        s_capital[i] = toupper(s[i]);
    }
    printf("%s", s_capital);
}

1 Answer 1

2

string s = "hello"; declares a string literal. By definition, it is immutable. If you try to change a char in that string, you will segfault.

Have a look at my post about string literals for more info.

Also, you'll learn more about this in Week 4, but your line string s_capital = s; does not make a copy of the string called s. It simply creates a new variable that "points" to the same part of memory. That is why you cannot change s_capital either.

3
  • 1
    maybe a comment about what string s_capital = s; does?
    – Cliff B
    Commented Dec 29, 2020 at 21:34
  • 2
    have done so @CliffB
    – curiouskiwi
    Commented Dec 30, 2020 at 1:18
  • 1
    Thanks so much for this :) The way I solved it was to define a character array, and then specify each value in the array as the uppercase variant of each character in my string. Commented Dec 30, 2020 at 13:40

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .