Pointers Misc Demo:
The same function is called two times to perform different functions:
1, basic operation, function allocated memory
#include <stdio.h> #include <stdlib.h> #include <string.h>int Getcontentlen (Char *filename,char **buf,int *len) { char *tmp = (char*) malloc ( if) (TMP == null) return -1; strcpy (tmp, "Hello!"); *len = strlen (TMP); *buf = tmp; return 0;} Int main () { int ret = 0; char *filename = "MyFile.txt"; char *buf = null; int len = 0; &nBsp; ret = getcontentlen (Filename,&buf,&len); if (ret != 0) {Return ret;} printf ("%s \n", buf); printf ("%d \n", Len); if (buf != null) free (BUF); return 0;} Compile and run: [Email protected]:~/high$ gcc -g -o run main.c && ./run hello! 6 [email protected]:~/high$
#include <stdio.h> #include <stdlib.h> #include <string.h>int Getcontentlen (Char *filename,char *buf,int *len) { if (buf == null) { *len = 10; return 0; } else { strncpy (buf, "goog morning!", ten); } return 0;} Int main () { int ret = 0; char *filename = "MyFile.txt"; int len = 0; ret = getcontentlen (Filename,null,&len); char *buf = (char *) malloc (+); ret = getcontentlen (Filename,buf,&len); printf ("%s \n" , buf); return 0;} Compiling: [Email protected]:~/high$ gcc -g -o run main.c && ./run goog morni [email protected]:~/high$
This article is from the "Soul Bucket" blog, please be sure to keep this source http://990487026.blog.51cto.com/10133282/1792292
C Improved 6 pointers Miscellaneous API function encapsulation, sockets encapsulation, memory leak detection, log library