0

My goal is to figure out how to append to a new string. Why does top code work but bottom code gives error? Aren't they the same? Try it out.

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

int main (void)
{
  string p = get_string("enter: "); // enter poo
  p[0] = 65;
  printf("%s\n", p);
}

int main (void)
{
  string p = "poo";
  p[0] = 65;
  printf("%s\n", p);
}
2

The top code uses get_string to get you a string that is mutable (ie, can be changed).

The second code declares what is called a "string literal" that is stored in read-only memory. If you try to change an individual char in that string, you will get a segfault crash, as you have seen.

If you need to create your own string, you should use a char array instead, since learning how to create a string like get_string does won't be taught until future weeks.

(For Caesar is not actually necessary to create any strings. You can simply print each ciphered char as you go, or change the original string and then print that at the end.)

1
  • Oh I see. Thanks I changed the original string and I solved it.
    – firechip
    Jul 19 '19 at 2:05

You must log in to answer this question.

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