C - Pass and operate on char pointers and pointer-to-pointer -


as novice c language fighting pointers, specially double pointers.

my intention

  1. malloc char pointer in main
  2. pass malloced pointer different functions
  3. get result of each function within same pointer
  4. free pointer in main

this code:

#include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h>  void process1(char **pointer) {     //this should take , change pointer value x     (*pointer)[0] = 'x';     (*pointer)[1] = '\0'; }  void process2(char **pointer) {     //this should take pointer, free , null it, new malloc , set pointer value y     char* p = *pointer;     free(p);     p = null;      p = malloc(sizeof(char)*2);     p[0] = 'y';     p[1] = '\0';      *pointer = p; }  void main() {     char* p = malloc(sizeof(char)*2);     p[0] = 'a';     p[1] = '\0';     //should print     printf("%s\n",p);     process1(&p);     //should print x     printf("%s\n",p);     process2(&p);     //should print y     printf("%s\n",p);      free(p);     p=null;  }  //this output expectd sh-4.2$ main x y 

my questions are:

  1. is practice?
  2. am leaking memory in function process2 when mallocing p pointer? need free p pointer somewhere?

this program well-behaving. frees allocated memory, , not write outside bounds of allocated memory.

what process2 doing fine perspective of reallocating allocated memory. in particular case, you're allocating same amount of memory before, in general if such function might expanding allocated memory makes sense pass double pointer modify pointer variable in calling function.

as process1, pointer being passed in address not being modified, points to, there's no need double pointer here. instead define as:

void process1(char *pointer) {     pointer[0] = 'x';     pointer[1] = '\0'; } 

and call this:

process1(p); 

Comments

Popular posts from this blog

python Tkinter Capturing keyboard events save as one single string -

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

javascript - Z-index in d3.js -