But that prints nothing, and no error. What went wrong?
des does not point to the start of the string anymore after doing (*des++ = *src++). In fact, des is pointing to one element past the NUL character, which terminates the string, thereafter.
Thus, if you want to print the string by using printf("%s\n",des) it invokes undefined behavior.
You need to store the address value of the "start" pointer (pointing at the first char object of the allocated memory chunk) into a temporary "holder" pointer. There are various ways possible.
#include <stdio.h> #include <stdlib.h> int main (void) { char *des = malloc(sizeof(char) * 10); if (!des) { fputs("Error at allocation!", stderr); return 1; } char *tmp = des; for (const char *src = "abcdef"; (*des++ = *src++) ; ); des = temp; printf("%s\n",des); free(des); }
Alternatives:
#include <stdio.h> #include <stdlib.h> int main (void) { char *des = malloc(sizeof(char) * 10); if (!des) { fputs("Error at allocation!", stderr); return 1; } char *tmp = des; for (const char *src = "abcdef"; (*des++ = *src++) ; ); printf("%s\n", tmp); free(tmp); }
or
#include <stdio.h> #include <stdlib.h> int main (void) { char *des = malloc(sizeof(char) * 10); if (!des) { fputs("Error at allocation!", stderr); return 1; } char *tmp = des; for (const char *src = "abcdef"; (*tmp++ = *src++) ; ); printf("%s\n", des); free(des); }
Side notes:
"abcdef\0" - The explicit \0 is not needed. It is appended automatically during translation. Use "abcdef".
Always check the return of memory-management function if the allocation succeeded by checking the returned for a null pointer.
Qualify pointers to string literal by const to avoid unintentional write attempts.
Use sizeof(char) * 10 instead of plain 10 in the call the malloc. This ensures the write size if the type changes.
int main (void) instead of int main (void). The first one is standard-compliant, the second not.
Always free() dynamically allocated memory, since you no longer need the allocated memory. In the example above it would be redundant, but if your program becomes larger and the example is part-focused you should free() the unneeded memory immediately.
for loopin an uncommon way and called it cramming? Wellfor loopis pretty basic concept among all programming, and c has the advantage to use it whatever way you like. I use it a lot in different way thatfor(int i =0;i<10;i++)like you are used to, but that is just my preference.(*des++ = *src++)part of yourforloop has 6 things going on at once. Yeah - you crammed too much there.