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

用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
", p); //输出结果

    //如何把搜索到的结果envenidos a todos保存到新的字符串中呢?
    char * t = (char *)malloc(strlen(p)+1);
    strcpy(t, p);
    printf("%s
", 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
", 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 ", t); *p = c; printf("%s ", s); return 0; }
原文地址:https://www.cnblogs.com/profesor/p/13159428.html