用指针函数给指针进行初始化

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *Init()//指针函数
{
    char *tmp = (char *)malloc(sizeof(char)*10);
    return tmp;
}

int main()
{
    char *str;
    str = Init();
    strcpy(str, "hello");
    printf("%s\n", str);
    return 0;
}

补充: 也可以传指针的地址,, 对指针进行初始化 

include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
void memoryInit(char **str)
{
    *str = (char *)malloc(sizeof(char) * 20);
}
 
int main()
{
    char *ptr = NULL;
    memoryInit(&ptr);
    strcpy(ptr, "hello");
    printf("%s\n",ptr);
 
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_42720316/article/details/81748039
今日推荐