leo*_*n22 4 c string pointers c-strings
#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;
}
Run Code Online (Sandbox Code Playgroud)
为什么 without malloc 的定义也是可能的,和之间anotherStr有什么区别?anotherStrdynamicStr
这是可能的,因为这里:
char *anotherStr = "This is another string";
Run Code Online (Sandbox Code Playgroud)
字符串文字(“这是另一个字符串”)被分配在其他地方,并且anotherStr仅设置为指向内存中的该区域。例如,您无法更改此字符串。更多这里
这里:
char *dynamicStr = malloc(sizeof(char) * 32);
memcpy(dynamicStr, "test", 4);
Run Code Online (Sandbox Code Playgroud)
给定大小的内存被分配到某处,并返回指向它的指针,该指针被分配给dynamicStr。然后您使用 写入该位置memcpy。与前面的示例相反,您可以在此位置写入/修改内容。但您需要稍后释放该内存。
附:在上面的示例中,您在打印时触发未定义行为,因为您用于memcpy复制并复制了 4 个字符 - 并且也忘记复制空终止符。strcpy代替使用。
| 归档时间: |
|
| 查看次数: |
3305 次 |
| 最近记录: |