[英]C char pointer with/without malloc
#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;
}
为什么没有malloc的anotherStr
定义也是可能的, anotherStr
和dynamicStr
什么dynamicStr
?
可能是因为这里:
char *anotherStr = "This is another string";
字符串常量(“ This is another string”)被分配在其他位置,并且anotherStr
仅设置为指向内存中的该区域。 例如,您不能更改此字符串。 这里更多
这里:
char *dynamicStr = malloc(sizeof(char) * 32);
memcpy(dynamicStr, "test", 4);
给定大小的内存分配在某个地方,并返回指向它的指针,该指针分配给dynamicStr
。 然后,您使用memcpy
写入该位置。 与之前的示例相反,您可以在此位置写入/修改内容。 但是您需要稍后释放此内存。
PS。 在上面的示例中,您在打印时触发了“未定义行为”,因为您使用memcpy
进行了复制并复制了4个字符-并且也忘记了复制空终止符。 请改用strcpy
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.