#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
const char *str = "This is a string";
char *strCpy = strdup(str); // new copy with malloc in background
printf("str: %s strCpy: %s\n", str, strCpy);
free(strCpy);
char *anotherStr = "This is another string";
printf("anotherStr: %s\n", anotherStr);
char *dynamicStr = malloc(sizeof(char) * 32);
memcpy(dynamicStr, "test", 4+1); // length + '\0'
printf("dynamicStr: %s\n", dynamicStr);
free(dynamicStr);
return 0;
}
Why is the definition of anotherStr
without malloc also possible, and what are the differences between anotherStr
and dynamicStr
?