Angel David Yaguana Hernandez
/
CPP_malloc
malloc, descripcion y ejemplo
main.cpp@0:984f552374ff, 2012-04-03 (annotated)
- Committer:
- sherckuith
- Date:
- Tue Apr 03 21:01:54 2012 +0000
- Revision:
- 0:984f552374ff
malloc, descripcion y ejemplo
Who changed what in which revision?
User | Revision | Line number | New contents of line |
---|---|---|---|
sherckuith | 0:984f552374ff | 1 | #include "mbed.h" |
sherckuith | 0:984f552374ff | 2 | /* malloc example: string generator*/ |
sherckuith | 0:984f552374ff | 3 | #include <stdio.h> |
sherckuith | 0:984f552374ff | 4 | #include <stdlib.h> |
sherckuith | 0:984f552374ff | 5 | |
sherckuith | 0:984f552374ff | 6 | int main () |
sherckuith | 0:984f552374ff | 7 | { |
sherckuith | 0:984f552374ff | 8 | int i,n; |
sherckuith | 0:984f552374ff | 9 | char * buffer; |
sherckuith | 0:984f552374ff | 10 | |
sherckuith | 0:984f552374ff | 11 | printf ("How long do you want the string? "); |
sherckuith | 0:984f552374ff | 12 | scanf ("%d", &i); |
sherckuith | 0:984f552374ff | 13 | |
sherckuith | 0:984f552374ff | 14 | buffer = (char*) malloc (i+1); |
sherckuith | 0:984f552374ff | 15 | if (buffer==NULL) exit (1); |
sherckuith | 0:984f552374ff | 16 | |
sherckuith | 0:984f552374ff | 17 | for (n=0; n<i; n++) |
sherckuith | 0:984f552374ff | 18 | buffer[n]=rand()%26+'a'; |
sherckuith | 0:984f552374ff | 19 | buffer[i]='\0'; |
sherckuith | 0:984f552374ff | 20 | |
sherckuith | 0:984f552374ff | 21 | printf ("Random string: %s\n",buffer); |
sherckuith | 0:984f552374ff | 22 | free (buffer); |
sherckuith | 0:984f552374ff | 23 | |
sherckuith | 0:984f552374ff | 24 | return 0; |
sherckuith | 0:984f552374ff | 25 | } |