首页 > 其他 > 详细

[C]malloc(), free()函数的应用

时间:2020-06-18 19:59:33      阅读:47      评论:0      收藏:0      [点我收藏+]

用strchr搜索字符,并把搜索到的字符串保存到新字符串中

 

#include <stdio.h>
#include <string.h>
#include <stdlib.h> //用于malloc(), free()函数
int main() {
    char s[] = "Bienvenidos a todos";
    char * p = strchr(s, e); //通过这个方法找到了第一个e的地址,如何找下一个e呢?
    printf("%s\n", p); //输出结果

    //如何把搜索到的结果envenidos a todos保存到新的字符串中呢?
    char * t = (char *)malloc(strlen(p)+1);
    strcpy(t, p);
    printf("%s\n", t);
    free(t); //有借有还
    return 0;
}

 

 // 如果想要搜索到的结果envenidos a todos之前的内容Bi保存到新的字符串中,如何做呢?

#include <stdio.h>
#include <string.h>
#include <stdlib.h> //用于malloc(), free()函数
int main() {
    char s[] = "Bienvenidos a todos";
    char * p = strchr(s, e); //通过这个方法找到了第一个e的地址,如何找下一个e呢?
    printf("%s\n", p); //输出结果
// 如果想要搜索到的结果envenidos a todos之前的内容Bi保存到新的字符串中,如何做呢? char c = *p; //临时保存p地址所指的值 *p = 0; char * t = (char *)malloc(strlen(s)+1); //这时获取的s长度就会只是Bi长度 strcpy(t, s); printf("%s\n", t); *p = c; printf("%s\n", s); return 0; }

 

[C]malloc(), free()函数的应用

原文:https://www.cnblogs.com/profesor/p/13159428.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!