#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main() {
char *str1;
str1 = malloc(4); //malloc()中的数字以字节为单位
char str2[]= "abc";
//char *str2 = "abc";
strcpy(str1,str2);
printf("%s\n",str1);
return 0;
}
如果注释掉str1=malloc(4)就会报错,因为没有给指针分配内存空间。
本文通过一个C语言示例代码,详细解释了如何使用malloc函数为字符指针分配内存,并通过strcpy函数进行字符串复制。文章强调了在进行字符串操作前确保已正确分配内存的重要性。

501

被折叠的 条评论
为什么被折叠?



