Code:#include <stdio.h> #include <string.h> #include <stdlib.h> /* scpy1() copies string to a same size char array. */ void scpy1(char d[], const char s[]); /* scpy2() tries to allocate memory to d[] inside the body. */ void scpy2(char d[], const char s[]); void main() { char a[] = "This is a line of ASCII string"; char* b = 0; char* c = 0; printf("a : %s\n", a); // a has a string. printf("b : %s\n", b); // b is yet NULL. printf("c : %s\n", c); // c is yet NULL. /* memory to b is allocated in main(). */ b = (char*)malloc(strlen(a) + 1); scpy1(b, a); // b is passed with its already allocated memory. scpy2(c, a); // but c is passed as NULL. printf("a : %s\n", a); printf("b : %s\n", b); // shows a is copied to b. printf("c : %s\n", c); // shows c is still NULL. /* --------------------------------------------- */ /* Why scpy2() behaves for c the way it is? */ /* How can I assign memory to c inside scpy2()? */ /* --------------------------------------------- */ } /* scpy1() copies string to a same size char array. */ void scpy1(char d[], const char s[]) { int i = 0; int j = 0; if ((s != NULL) && (d != NULL)) { i = strlen(s); for (j = 0; j <= i; ++j) { d[j] = s[j]; } } } /* scpy2() tries to allocate memory to d[] inside the body. */ void scpy2(char d[], const char s[]) { int i = 0; int j = 0; if ((s != NULL) /*&& (d = NULL)*/) { i = strlen(s); /* Try to allocate memory inside this scpy2(). */ d = (char*)malloc(strlen(s) + 1); /* ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ */ for (j = 0; j <= i; ++j) { d[j] = s[j]; } } }



LinkBack URL
About LinkBacks


