Advertisement
math230

String literals

Jul 20th, 2020
1,563
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.82 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include<string.h>
  4. void delete_str(char *str);
  5. int main()
  6. {
  7.     char*       dst1 = "string Literal";  //can't change the contents; note that address of char* dst1 is different seg from char safedst[]
  8.     //dst1[0] = 'T';  //crashes. no compiler running
  9.     const char* dst2 = "string Literal";  //can't change the contents
  10.     //dst2[0] = 'T';  //won't compile. dst2[] is read-only location
  11.     char        source[] = "Sample string";
  12.  
  13.     char        safedst[] = "sample String alternative dest";
  14.     //safedst[0] = 'T';  //allowed
  15.  
  16.     //strcpy(dst1,source);    //No warning or error, just Undefined Behavior; pgm crashes
  17.     //strcpy(dst2,source);    //Compiler issues a warning; pgm crashes
  18.     strcpy(safedst, source);  // No warning or error.  No crash
  19.     puts(safedst);
  20. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement