C/C++ 矢量和参考参数

C/C++ Vector and reference parameter

本文关键字:参考 参数 C++      更新时间:2023-10-16

我想在我的主函数中接收一个 VECTOR。代码是这样的。

int myfunction(void);

int main(){
    int p = myfunction(void);
    std::cout << p[2] << std::endl;
};

int myfunction(void){
      int new array[4]={0,1111,2222,3333};
      int *p;
      p = array;
      return p; 
};

在C++中,你会做:

std::vector<int> myfunction();
int main(){
    std::vector<int> p = myfunction();
    std::cout << p[2] << std::endl;
}
std::vector<int> myfunction(){
    return std::vector<int>{0,1111,2222,3333};
}

在 C 中,您可以执行以下操作:

int* myfunction(void);
int main(void){
    int* p = myfunction();
    printf("%dn", p[2]);
    free(p);
}
int* myfunction(void){
    int tmp[] = {0,1111,2222,3333};
    int* array = (int*)malloc(sizeof(tmp));
    memcpy(array, &tmp, sizeof(tmp));
    return array;
}

现在,如果你在这段代码上遇到问题,我建议你去挑选一本好的C或C++书(无论你对哪个感兴趣)并阅读该语言的基础知识,因为你看起来真的很困惑。