Thread: beginner question about runtime error

  1. #1
    Registered User
    Join Date
    Jun 2018
    Posts
    1

    beginner question about runtime error

    Hi there,

    Does anybody know why this code results in a run time error?




    Code:
    char *code = "ASCII";
    char* s;
    s = code;
    *(code+1) = *(s+1);


  2. #2
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    This is what happens when you try to modify a string literal. If you are going to use a string literal this way, make sure the pointer type is const char * so that the compiler can help you spot mistakes with warnings.

    Although I would also like to point out that *(code+1) = *(s+1); does nothing you'd see since these are two ways to reference the same character, anyway.

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    37,530
    If you saw this in a book which suggests it should work, then you have a very old book.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. beginner's question: simple class usage compiler error.
    By yaraeovento in forum C++ Programming
    Replies: 3
    Last Post: 05-12-2013, 03:24 PM
  2. Beginner question: Error with the compiler
    By d3lilley in forum C++ Programming
    Replies: 5
    Last Post: 11-30-2010, 06:05 PM
  3. Replies: 10
    Last Post: 08-12-2008, 03:42 AM
  4. compile time error or runtime error?
    By George2 in forum C# Programming
    Replies: 3
    Last Post: 05-07-2008, 07:08 AM
  5. runtime error
    By poorman in forum C Programming
    Replies: 1
    Last Post: 06-23-2002, 03:19 AM

Tags for this Thread