Created
March 3, 2018 00:03
-
-
Save glennlopez/223a95a83f1173450469420b63e53f90 to your computer and use it in GitHub Desktop.
This file contains 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 <cs50.h> | |
/* | |
This program takes a user input get_string | |
and copy it into heap memory | |
*/ | |
int main(){ | |
int usrStr_size = 0; | |
//ask user for string | |
char *usrStr = get_string("User String: "); | |
if(!usrStr){ //not enough memory | |
return 1; | |
} | |
//print out user string + count string size | |
printf("Stack Memory: "); | |
for(usrStr_size = 0; usrStr[usrStr_size] != '\0'; usrStr_size++){ | |
printf("%c", usrStr[usrStr_size]); | |
} | |
printf("\n"); | |
//allocate heap memory | |
char *usrStr_copy = malloc((usrStr_size + 1) * sizeof(char)); | |
if(!usrStr_copy){ //not enough memory | |
return 1; | |
} | |
//copy user string into heap memory | |
/* | |
for(int i = 0; i < usrStr_size; i++){ | |
usrStr_copy[i] = usrStr[i]; | |
} | |
*/ | |
usrStr_copy[0] = 'X'; | |
usrStr_copy[1] = 'L'; | |
usrStr_copy[2] = 'A'; | |
usrStr_copy[3] = 'G'; | |
usrStr_copy[4] = '0'; | |
usrStr_copy[5] = 'C'; | |
//print out contents of heap memory | |
printf("Heap Memory: "); | |
for(int i = 0; usrStr_copy[i] != '\0'; i++){ | |
printf("%c", *(usrStr_copy + i)); | |
} | |
printf("\n"); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment