[英]C++ error variable declared void when passing array into function
I'm trying to refresh myself in C++ before my college starts again and I ran into some problems.在我的大学重新开始之前,我试图用 C++ 来更新自己,但我遇到了一些问题。 I'm using a bubblesort function given by my professor and I'm struggling to run it in my int main.
我正在使用我的教授提供的冒泡排序函数,并且我正在努力在我的 int main 中运行它。 The function parameters is
bubblesort(int *a, int length)
, so I used bubblesort(a, sizeof(a)/sizeof(*a) )
.函数参数是
bubblesort(int *a, int length)
,所以我使用了bubblesort(a, sizeof(a)/sizeof(*a) )
。 The compiler shows an error ' a ' is declared void.编译器显示错误“a”被声明为无效。 I tried searching up for an answer if I made a mistake but I couldn't catch my error.
如果我犯了错误,我尝试寻找答案,但我无法发现我的错误。 If you understand why I am getting this error can you please explain in detail what I'm missing or doing wrong.
如果您明白为什么我会收到此错误,请详细解释我遗漏了什么或做错了什么。
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
void bubblesort(int *a, int length)
{
int i, temp, finished = 0;
while(!finished)
{
finished = 1;
for( i = 0; i< length-1; i++)
{
if(a[i] > a[i+1])
{
temp = a[i];
a[i] = a[i+1];
a[i+1] = temp;
finished = 0;
}
}
}
}
int main()
{
int a[] = {5,1,7,9,4,3};
for (int i = 0;i < sizeof(a)/sizeof(*a);i++){ cout << a[i]; }
cout << endl;
void bubblesort(a, sizeof(a)/sizeof(*a));
for (int i = 0;i < sizeof(a)/sizeof(*a);i++){ cout << a[i]; }
}
You don't need return type in function call.函数调用中不需要返回类型。
Remove void
from the line从行中删除
void
void bubblesort(a, sizeof(a)/sizeof(*a));
and make it并使它
bubblesort(a, sizeof(a)/sizeof(*a));
You can't specify the return type of a function when making a function call, so you need:进行函数调用时不能指定函数的返回类型,因此需要:
bubblesort(a, sizeof(a)/sizeof(*a)); // no void at the beginning
However, you have a fixed-size array, so the call could also simply be:但是,您有一个固定大小的数组,因此调用也可以简单地为:
bubblesort(a, std::size(a));
Also, this loop:此外,这个循环:
for (int i = 0;i < sizeof(a)/sizeof(*a);i++){ cout << a[i]; }
can be rewritten like this:可以这样改写:
for (int elem : a)
cout << elem;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.