| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 865 人关注过本帖
标题:c语言realloc使用
只看楼主 加入收藏
liu556456qw
Rank: 1
等 级:新手上路
帖 子:1
专家分:0
注 册:2017-8-16
结帖率:0
收藏
已结贴  问题点数:20 回复次数:1 
c语言realloc使用
写了一个求交集的函数,使用到了realloc函数,有一个地方不理解,恳请大家指点

int *arrayIntersection(int *item, int item_total, int *list, int list_total, int *total_count)
{
    int count = 1;
    int total = 0;
    int *res = (int *)malloc(sizeof(int)*count);
    int *p = res;

    int i,j;
    i = j = 0;

    while(i < item_total && j < list_total){
        if(item[i] < list[j]){
            i++;
        }else if(list[j] < item[i]){
            j++;
        }else{
            count++;
            res = (int *)realloc(res, sizeof(int)*count);
            res[total++] = item[i];
            i++;j++;
        }
    }
   
   
    *total_count = total;

    return p;
}


--------------------------------------------------
res = (int *)realloc(res, sizeof(int)*count);
res[total++] = item[i];
赋值的时候为啥不能用*res++,必须使用数组的形式,另外请大家看看,代码有没有什么需要改进的地方


搜索更多相关主题的帖子: realloc int item count res 
2017-08-16 23:37
吹水佬
Rank: 16Rank: 16Rank: 16Rank: 16
等 级:版主
威 望:451
帖 子:10570
专家分:43031
注 册:2014-5-20
收藏
得分:20 
以下是引用liu556456qw在2017-8-16 23:37:52的发言:
res = (int *)realloc(res, sizeof(int)*count);
res[total++] = item;
赋值的时候为啥不能用*res++,必须使用数组的形式,另外请大家看看,代码有没有什么需要改进的地方

res++意味着要改变res的地址属性。
res是由realloc()返回的地址值,最好不要随便改变。否则,下次realloc(res,..)或释放资源时可能会出异常。
2017-08-17 07:49
快速回复:c语言realloc使用
数据加载中...
 
   



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

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