Advertisement
D3ad

Untitled

Nov 13th, 2014
182
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.05 KB | None | 0 0
  1. /* Author: Jiri Zahradnik
  2.  * Date 13. Nov 2014
  3.  * Purpose: pointer logic demonstration
  4. */
  5.  
  6. #include <stdio.h>
  7.  
  8. int main(){
  9.     int *i; /* here we have a pointer */
  10.     /* pointer is just an arrow which points, through dereferencing (*) and referencing(&)
  11.        we can get its adress(reference) or value stored at that adress(dereference)
  12.     */
  13.     i = malloc(sizeof(int));/* to store anything, we must allocate memory for value
  14.                    malloc returns pointer(adress) of allocated memory
  15.                 */
  16.     /* now we want to store a value in that memory, we use dereference(symbol: *), it means this:
  17.         Program! I want to write THIS value in THIS memory pointed by pointer i
  18.     */
  19.  
  20.     *i = 5;
  21.  
  22.     /* what we do NOT want to do, is modifying adress, so this:
  23.         &i = 5;
  24.        will change adress and not only we lose access to that memory block,
  25.        we cause crash of that program
  26.     */
  27.    
  28.     /* now we want to print adress of i */
  29.     printf("%0xp\n", &i);  
  30.     /* now we want to print value of i */
  31.     printf("%d\n", i);
  32.     /* and now we want to free memory */
  33.     free(i);
  34.  
  35.     return 0;
  36. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement