Last active
December 9, 2019 09:35
-
-
Save winhtut/1d84c1bea8a179270ed43422a7bf3160 to your computer and use it in GitHub Desktop.
Dynamic Memory Allocation
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> | |
int main(){ | |
int i=0; | |
int *ptr; | |
int sum=0; | |
ptr=calloc(6 , sizeof(int)); | |
printf("created memory of each block size %d \n",sizeof(ptr)); | |
if( ptr==NULL){ | |
printf("somethings wrong with memory alloc\n"); | |
}else{ | |
for( i=0; i<6 ; i++){ | |
*(ptr+i)=i; | |
sum +=*(ptr+i);//sum=1 | |
printf(" %d : value is %d\n",i,sum); | |
} | |
} | |
printf("sum of all values at each block = %d\n",sum); | |
free(ptr);//de-alloc | |
printf("memory was de-allocated"); | |
return 0; | |
} | |
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> | |
int main(){ | |
int *ptr; | |
ptr= malloc(5* sizeof(*ptr)); | |
if(ptr!= NULL){ | |
printf(" memory block created at %d\n",ptr); | |
*(ptr+0)=10; | |
*(ptr+1)=20; | |
*(ptr+2)=30; | |
*(ptr+3)=40; | |
*(ptr+4)=50; | |
}else{ | |
printf(" cannot create ;"); | |
} | |
int i=0; | |
for(i=0; i<6; i++){ | |
printf(" %d value is %d \n",i,*(ptr+i)); | |
} | |
free(ptr);//de-alloc | |
printf("memory was de-allocated"); | |
return 0; | |
} |
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> | |
int main(){ | |
char *ptr; | |
ptr = (char*)malloc(10); | |
strcpy(ptr,"re"); | |
printf(" %s , address at : %d\n",ptr,ptr); | |
ptr=(char *)realloc(ptr,2); | |
strcat(ptr,"Vijja"); | |
printf("data is : %s , address = %u",ptr,ptr); | |
free(ptr);//de-alloc | |
printf("\nmemory was de-allocated"); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment