传递一个数组在C参数++ [英] Passing an array as an argument in C++

查看:151
本文介绍了传递一个数组在C参数++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写一个归并排序功能,而现在我只是用一个测试用例阵列(没有输入 - 这是静态的,现在是)。我不知道如何传递一个数组作为参数。这里是我的code现在:

I'm writing a merge sort function, and right now I am just using a test case array (there is no input - this is static, for now). I don't know how to pass an array as an argument. Here is my code right now:

//merge sort first attempt

#include <iostream>
#include <algorithm>
#include <vector>

int mergeSort(int[]);
int main()
{
int originalarray[] = {1, 3, 5, 7, 9, 2, 4, 6, 8, 10};
mergeSort(originalarray[]);
}

int mergeSort(int[] originalarray)
{
int num = (sizeof(originalarray)/sizeof(int));
std::vector<int> original(num);

if (num > 2) {
    return num;
}

// Fill the array using the elements of originalarray
// This is just for demonstration, normally original will be a parameter,
// so you won't be filling it up with anything.
std::copy(originalarray, originalarray + num, original.begin());

// Create farray and sarray of the appropriate size
std::vector<int> farray(num / 2);
std::vector<int> sarray(num - farray.size());

// Fill those using elements from original
std::copy(original.begin(), original.begin() + farray.size(), farray.begin());
std::copy(original.begin() + farray.size(), original.end(), sarray.begin());

mergeSort(farray);
mergeSort(sarray);

}

请注意,该归并功能并不实用,因为我还没有想出如何将它们合并还没有(这是我的任务)。我希望让我的两个向量进行排序之前,我处理了,我不能编译,因为我需要传递一个数组作为参数这一点。我不明白的指针,因此,如果这是解决方案,我的借口是无知。我正在学习编程,现在,使用C ++作为第一语言,只有语言的功能基本掌握。感谢您的帮助。

Note that this mergeSort function is not functional, as I have not figured out how to merge them yet (that's my assignment). I would like to get my two vectors sorted before I deal with that, and I can't compile this because of my need to pass an array as an argument. I don't understand pointers, so if that is the solution, my excuse is ignorance. I'm learning programming right now, with C++ as a first language, and only have a basic grasp of the language's features. Thanks for the help.

推荐答案

您不应该使用的sizeof(originalarray)/的sizeof(INT)这样。这将仅适用于静态声明数组工作(大小在编译时已知)。你必须一起传递的大小与它。你为什么不只是做一个矢量从数组中,并通过它来代替?

You should not use sizeof(originalarray)/sizeof(int) like that. It'll only work for statically declared arrays (the size is known at compile time). You have to pass the size along with it. Why don't you just make a vector out of the array and pass it instead?

侧面说明:的作为一个经验法则,始终注意的sizeof 将在编译时被翻译。因此,有没有办法,它可以知道作为参数传递的数组的大小。

Side Note: As a rule of thumb, always note that sizeof will be translated at compile time. So there's no way it could know the size of the array passed as an argument.

这篇关于传递一个数组在C参数++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆