字符指针如何用malloc
时间: 2023-11-27 12:07:42 浏览: 32
使用 `malloc` 分配字符指针的内存空间可以按照以下步骤进行:
1. 定义字符指针变量
```c
char *str;
```
2. 使用 `malloc` 分配内存空间
```c
str = (char*) malloc(sizeof(char) * n); // n为需要分配的内存空间大小
```
3. 判断内存空间是否分配成功
```c
if(str == NULL) {
printf("内存分配失败!\n");
return -1;
}
```
4. 使用分配得到的内存空间进行操作,如赋值、拷贝等
```c
strcpy(str, "Hello World!"); // 字符串赋值操作
```
5. 最后使用 `free` 函数释放内存空间
```c
free(str);
```
完整示例代码如下:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
char *str;
int len = 20;
str = (char*) malloc(sizeof(char) * len);
if(str == NULL) {
printf("内存分配失败!\n");
return -1;
}
strcpy(str, "Hello World!");
printf("分配的内存空间为:%d\n", len);
printf("字符串为:%s\n", str);
free(str);
return 0;
}
```