Advertisement
paulogp

malloc

Jul 19th, 2011
266
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.81 KB | None | 0 0
  1. // title: malloc
  2. // ide: apple xcode
  3. // author: paulogp
  4.  
  5.  
  6. #include <stdio.h>
  7. #include <string.h>
  8. #include <stdlib.h>
  9.  
  10. int main (int argc, const char * argv[])
  11. {
  12.     char the_str[200] = "hello world";
  13.     char *the_ptr; // apontador para um conjunto de chars
  14.    
  15.     // printf("string: ");
  16.     // gets(the_str);
  17.    
  18.     // alocar memoria
  19.     the_ptr = (char *) malloc(strlen(the_str) + 1); // incluir '\0' na contagem
  20.    
  21.     if (the_ptr == NULL)
  22.     {
  23.         puts("erro na alocacao da memoria\n");
  24.         return 0;
  25.     }
  26.     else
  27.     {
  28.         // "copia" the_str para the_ptr
  29.         strcpy(the_ptr, the_str);
  30.     }
  31.    
  32.     // output das duas strings
  33.     printf("string original: %s\ncopia: %s\n", the_str, the_ptr);
  34.    
  35.     // libertar memoria
  36.     free(the_ptr);
  37.  
  38.     return 0;
  39. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement