2014-06-19 57 views
-6
int *sub(int *A,int q) 
{ 
    int i = id(A,q)+1,j = id(A,q)-1; 
    int *l , *m ; 
    m = (int*)malloc(sizeof(int)); 
    *m = q; 
    l = m ; 
    for(i ; *(A+i) != '\0' && *(A + i) >= q ; ++i) 
    { 
     ++l = (int*)malloc(sizeof(int)); 
     *l = *(A+i); 
    } 
    ++l = (int*)malloc(sizeof(int)); 
    *l = '\0'; 
    for(j ; j>=0 && *(A + j) >= q ; j--) 
    { 
     --m = (int*)malloc(sizeof(int)); 
     *m = *(A+i); 
    } 
    for(i = 0 ; *(m + i) != '\0' ; i++) 
     cout<<*(m+i)<<"##\t"; 

    return m; 
} 

这是应该采取一个指针到一个一维数组(A),然后返回一个指针到另一个一维数组(M),其是A的子阵列,并且具有元件更大的功能大于或等于q(作为参数传递给函数sub
我想我操作int指针的方式存在一些问题。问题在C INT指针++

+2

如果你'malloc',你不是'C++'。 – StoryTeller

+2

这正是['std :: copy_if'](http://en.cppreference.com/w/cpp/algorithm/copy)的用途。请使用它并返回一个容器,而不是一个指向调用者现在必须释放的指针,就像50个内存泄漏一样。 – chris

+0

m不是一个二维数组,但你把它当作一个对象 –

回答

2
#include <iostream> 
#include <string> 
#include <vector> 
#include <algorithm> 


int _tmain(int argc, _TCHAR* argv[]) 
{ 
    std::vector<int> arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; 
    int q = 5; 
    std::vector<int> result; 
    std::copy_if(arr.begin(), arr.end(), std::back_inserter(result), [q](int i){return i >= q; }); 
    std::for_each(result.begin(), result.end(), [](int i){std::cout << i << std::endl; }); 
    getline(std::cin, std::string()); 
    return 0; 
} 
2

你不能保证m + i永远是'\ 0',至少不是已经被malloc化的空间。

在评论中提到的要点之上,比如确保所有空间都被适当地释放。这看起来像是一个巨大的内存泄漏到处都是。