a) Where I was wrong?where my programming logic getting fail?
Well, you did several things incorrectly. For one, void main
is non-standard; the return type for main
should be int
.
That being said, the real issue you're looking for has to do with the fact that q
is uninitialized, yet you attempt to still copy to memory through it (which is undefined behavior). To correct that, try allocating q
, e.g.
char *q = malloc(8);
Note you must then later also take care to free
the memory allocated here.
Aside from that, you're forgetting to copy the NUL
terminator, too.
*q = 0;
... after your copying loop. You also are printing q
after incrementing the pointer, so it will no longer be at the head of the string by the time of your printf
call. You should store a copy of the head in another variable. Additionally, be careful using a plain printf
without any new-lines, as the stream may be buffered and thus could remain unflushed -- use an explicit fflush(stdout);
b) How can I improve this code to get desired output?
Well, the first most straight-forward improvement I can think of is to use strcpy
.
#include <stdio.h>
main() {
const char p[] = "krishna";
char q[sizeof p];
strcpy(q, p);
puts(q);
getchar();
return 0;
}