Last active
January 13, 2016 20:17
-
-
Save svanellewee/ca2da57e0e5387aca2f3 to your computer and use it in GitHub Desktop.
Const Pointers in C
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <stdio.h> | |
| #include <stdlib.h> | |
| #include <string.h> | |
| int x,y; | |
| char *make_string(char* message) { | |
| char* val= (char*)malloc(sizeof(message)); | |
| strcpy(val,message); | |
| return val; | |
| } | |
| int main() { | |
| char const *mutable_pointer_immutable_char=make_string("hello"); | |
| char * const imutable_pointer_mutable_char=make_string("byebye"); | |
| const char *should_also_be_mutable_pointer_immutable_char=make_string("also_hello?"); | |
| printf("%s vs %s\n", mutable_pointer_immutable_char, imutable_pointer_mutable_char); | |
| imutable_pointer_mutable_char[0] = 'X'; | |
| printf("%s vs %s\n", mutable_pointer_immutable_char, imutable_pointer_mutable_char); | |
| // mutable_pointer_immutable_char[0] = 'y'; //--WRONG! read only location | |
| //should_also_be_mutable_pointer_immutable_char[0] = 'x'; //--WRONG!read only location | |
| // imutable_pointer_mutable_char = mutable_pointer_immutable_char; //-- WRONG! read only variable | |
| mutable_pointer_immutable_char = imutable_pointer_mutable_char; | |
| printf("%s vs %s\n", mutable_pointer_immutable_char, imutable_pointer_mutable_char); | |
| should_also_be_mutable_pointer_immutable_char = imutable_pointer_mutable_char; | |
| printf("%s vs %s vs %s\n", mutable_pointer_immutable_char, imutable_pointer_mutable_char, should_also_be_mutable_pointer_immutable_char); | |
| return 0; | |
| } | |
| /* hello vs byebye */ | |
| /* hello vs Xyebye */ | |
| /* Xyebye vs Xyebye */ | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment