I tried overwriting cipupperalphabet[j] from a A to a B, but it has caused a segmentation fault.

string upperalphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
string cipupperalphabet = upperalphabet;

int j = 0;
cipupperalphabet[j] = upperalphabet[j + 1];
printf("%c\n", cipupperalphabe[j]);

And, I'm not sure what went wrong.


I have a similar problem. When using David's code from Lecture 2 with the function of "toupper()" I get a segmentation fault error when instead of prompting the user for input, I myself define some string to be converted to uppercase letters:

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

int main(void)

string s = "JDLKFSJFjklj";

for (int i = 0, n = strlen(s); i < n; i++)
    s[i] = toupper(s[i]);
    //printf("%c", toupper(s[i]));
printf("%s\n", s);

string variables are a pointer to the first character of a string. For the value, you're using a string literal (a code representation of a string).

The compiler can store those characters in any way, but the most common way is to store the characters (including the null terminator) in some read-only area that gets loaded into memory on start of the application (so there's no extra copy step), string would then point to a location you are not allowed to write to.

Which means you cannot change characters in a string literal.

What you can do is use an array of char (if you want to interpret it as a string, make sure it has a null terminator after the actual characters). Note that this stores the characters on the stack, so the array exists only in the code block it is declared in, for example you cannot easily return it from a function. Later in the course you'll learn how to allocate memory on heap, which is not limited the same way (but has its own challenges).

You must log in to answer this question.

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