| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 2479 人关注过本帖
标题:函数调回指针的内存释放,(30分)请评价我编写的一个程序,
取消只看楼主 加入收藏
csj_65
Rank: 3Rank: 3
等 级:论坛游侠
帖 子:63
专家分:163
注 册:2010-3-12
结帖率:100%
收藏
已结贴  问题点数:30 回复次数:0 
函数调回指针的内存释放,(30分)请评价我编写的一个程序,
比如说你申明一个函数
char *string_cmp(char *str, const char *str1)
在其中你为要返回的指针用malloc申请了一快内存地址,那你该如该将其释放呢?
上次的回答我不是很满意,请大家看看我写的一个程序吧。

函数调回指针的内存释放(25分)
程序代码:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define MAX 256

static char *findchars;                //函数find_char的返回指针,返回被找到的字符,

char *find_char(char const *source, char const *chars);
//参数要搜索的字符串指针和给定字符集合
//带回找到的字符的集合的指针

int main (void)
{

    char *main_findchars;

    if ((main_findchars = (char *)malloc(sizeof(MAX))) == NULL)
    {
        printf("malloc error!\n");
        exit(1);
    }
    printf("we will find if there are members of the chars 'a,g9cd'");
    printf("in the string we input.\n");

    main_findchars = find_char("gfdgadgasd^dfe;(hdf8fgjgh,uy,i,oipujikthetwerqw", "a,g9cd");

    printf("the chars we find from the strings is %s\n", main_findchars);
    free(main_findchars);
    free(findchars);
    return 0;

}

char *find_char(char const *source, char const *chars)
{
    int count = 0;
    int i = 0;
    int j = 0;
    int charlen = strlen(chars);
    int sourcelen = strlen(source);
    int findc_yes_no[charlen];                        //数组每一位对应给定字符集中的相应的字符
                                                    //暂且称为开关数组,1和0代表有和没有
    if ((findchars = (char *)malloc(sizeof(chars))) == NULL)
    {
        printf("malloc error!\n");
        exit(1);
    }

    for(i = 0; i < charlen; i++)
    {
        findc_yes_no[i] = 0;
        *(findchars + i) = '\0';
    }

    for (i = 0; i < sourcelen; i++)
    {
        for(j = 0; j < charlen; j++)
        {
            if(*(source + i) == *(chars + j))
            {
                /*打印找到的字符在字符串中所处的位置*/
                printf("find char '%c' from the %dth of the strings\n", *(chars + j), i + 1);
                findc_yes_no[j] = 1;

            }
        }
    }

    for (i = 0; i < charlen; i++)                    //检查开关数组相应字符位
    {
        if (1 == findc_yes_no[i])                      //字符位若为1,把该字符放到findchars中去
        {
            *(findchars++) = *(chars + i);
            count++;
        }
    }

    return (findchars - count);

}
我是在函数中为返回指针开辟了动态存储空间,为了能在最后释放它,我把指针定义在函数外面,这样我就能在主函数中释放它,请问这种方法可行吗?有没有更好的方法,如果有请不吝赐教,非常感谢!
搜索更多相关主题的帖子: 内存 指针 函数 评价 
2010-04-29 18:57
快速回复:函数调回指针的内存释放,(30分)请评价我编写的一个程序,
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.020786 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved