- Forum
- General C++ Programming
- Why is it giving me an error in the func
Why is it giving me an error in the function call? Am I calling the array incorrectly?
|
|
Last edited on
First, please use code tags. See http://www.cplusplus.com/articles/jEywvCM9/
* Syntax highlight makes reading easier
* Line numbering helps commenting
* Preservation of (systematic) indentation helps to spot logical errors
* There is even a convenient shortcut to online compiler
Your code:
|
|
4:55: error: use of parameter outside function body before ']' token 4:58: error: use of parameter outside function body before ']' token In function 'int main()': 13:28: error: expected primary-expression before ']' token At global scope: 16:55: error: use of parameter outside function body before ']' token 16:58: error: use of parameter outside function body before ']' token In function 'int fillArrayPointer(...)': 19:20: error: 'R' was not declared in this scope 19:22: error: 'C' was not declared in this scope 25:12: error: 'A' was not declared in this scope 29:1: warning: control reaches end of non-void function [-Wreturn-type]
int fillArrayPointer(const int R, const int C, int a[R][C]);
error: use of parameter outside function body before ']' token
What is the size of the array?
It must be known during compilation (except the major dimension).
|
|
|
|
error: expected primary-expression before ']' token
|
|
|
|
In function 'int fillArrayPointer(int, int (*)[2])': 1:12: error: 'A' was not declared in this scope At global scope: 10:42: warning: unused parameter 'a' [-Wunused-parameter] In function 'int fillArrayPointer(int, int (*)[2])': 14:1: warning: control reaches end of non-void function [-Wreturn-type]
* You create dynamic array B on row 4 but you neither delete nor return it.
* You declare int a
on line 9 that masks parameter int a[][C]
from line 1
* You declare int a
inside loop, so effectively the loop is:
|
|
* Wait, the R and C are effectively constants. The loop is:
|
|
But the array does not have element A[2][2]
, nor row A[2]
. The last valid element of 2*2 matrix is A[1][1]
.
* Finally, your function should return one int value. It does not.
Is that what you are trying to achieve?
|
|
Thank you for all you help guys,
I just wanted to know the correct way to call a 2D array, but I’m just very confused now There are just some things I don’t understand in your code, like lines 4, 7, and 21 in seeplus’s code. Maybe it’s because I haven’t gotten that far in c++ :/
Please just tell me how I can call the function fillArrayPointer in the simplest way possible
Lines 3 & 4 are a way of obtaining the dimension sizes of an array without having to specify these as separate function parameters. R & C are the dimension sizes. This way means that to call the function in the simplest way possible all you need to do is to specify the array variable — as per L21
What don’t you understand about L7 and L21?
L7 B is a pointer to int which is initialised from the value of new int [R * C] which returns a pointer to memory of size R*C elements. D is also a pointer to int which is initialised to the value of B already obtained. D is used in setting the elements of the 1d array.
L21 D is a const pointer to const data which is initialised by the returned value from fillArrayPointer(A)
Thank you so much!
The fillArray can also be done simpler without using nested for loops:
|
|
However, rather than dealing with raw-pointers, a better C++ way would be to use a managed pointer.
|
|
Topic archived. No new replies allowed.
Это допустимый код в соответствии со стандартом c99, и этот фрагмент кода работает нормально на компиляторе gcc.
#include <stdio.h>
void foo( int n, int m, int a[][m]){
//do stuff
}
int main() {
int n,
m;
scanf("%d %d", &n, &m);
int a[n][m];
foo(n, m, a);
return 0;
}
Но эквивалентный код C ++ не работает на компиляторе g ++.
#include <cstdio>
#include <iostream>
using namespace std;
void foo( int n, int m, int a[][m]){
//do stuff
}
int main() {
int n,
m;
cin >> n >> m;
int a[n][m];
foo(n, m, a);
return 0;
}
Я получаю следующую ошибку.
error: use of parameter outside function body before ‘]’ token
void foo( int n, int m, int a[][m]){
Я не могу найти простое решение в C ++, так как оно доступно в C для этой проблемы.
-2
Решение
Прежде всего, вы должны заменить m
в int a[][m]
с некоторым постоянным значением, поскольку вы не можете использовать переменные для определения столбцов массивов в заголовках функций.
Во-вторых, вы не можете объявить массивы с переменным размером, как вы это сделали int a[n][m]
, здесь вы также должны использовать константы.
Но если вы хотите использовать массивы переменного размера, вы можете создавать массивы динамически.
int** a = new int*[n]; // It creates an array of pointers of size n
и затем вы можете перебрать этот массив указателей, чтобы выделить массив целых чисел для каждого из указателей.
for (int i = 0; i < n; i++){
a[i] = new int[m];
}
это создаст вам двумерный массив целых чисел динамически.
И чтобы передать этот массив в качестве аргумента какой-либо функции, вы можете использовать указатель на указатель.
void foo(int n, int m, int** a){
// here use it just like you use an array.
}
И когда вы закончите использовать массив, вы должны отменить выделение динамически размещенного массива.
for (int i = 0; i < n; i++){
delete[] a[i];
a[i] = 0;
}
delete[] a;
a = 0;
И если вам не нравится этот метод, вы всегда можете использовать вектор учебный класс.
vector<vector<int>> a(n, vector<int>(m));
Пройти vector
к функции.
void foo(const vector<vector<int>>& a){
size_t n = a.size();
size_t m = 0;
if (n > 0)
m = a[0].size();
// do your work
}
Когда используешь vector
вам не нужно беспокоиться о динамическом распределении или vector
класс сам обрабатывает подобные вещи.
1
Другие решения
Простое решение в C ++ для этой проблемы было бы использовать 2D вектор
vector <vector<int> > vecArray( 10, vector <int> (10) )
и передать его в функцию по ссылке &vec2DArray
,
#include <vector>
#include <iostream>
#include <iomanip>
using namespace std;// function to pass 2d vector array by reference &
void function( int n, int m, vector <vector<int> > & vec2DArray ) {
for (int y=0; y<10; y++ ){
for (int x=0; x<10; x++ ){
// perform some calculations
vec2DArray[y][x] = (y+1) * (x+1) *m *n;
}
}
}int main() {
cout<<"function to pass 2d vector array by reference & nn";
// create a 2D vector of dimension [10][10]
vector <vector<int> > vec2DArray( 10, vector <int> (10) );
int n=0, int m=0;
// call function, pass 2d vector array by reference &
function( 1, 1, vec2DArray );
// display calculation results
for (int y=0; y<10; y++ ){
for (int x=0; x<10; x++ ){
// display vec2DArray
cout << setfill(' ') << setw(2)<< vec2DArray[y][x] <<" ";
}
cout<<"n";
}
cout<<"n";cout<<"Press ANY key to close.nn";
cin.ignore(); cin.get();
return 0;
}
0
Извините, если название вводит в заблуждение.
Ниже я прикрепляю некоторые части своего кода, которые, по моему мнению, будут иметь отношение к пониманию ошибок, отмеченных компилятором.
#include <stdio.h>
size_t count_gen(const size_t rowbound,const size_t colbound,const int num,double input[][rowbound][colbound],double output[][colbound])
{
size_t i,j,row;
for(j = 0; j < colbound; ++j)
{
for(i = 0; i < rowbound; ++i)
{
for(row = 0; row < rowbound; ++row)
{
if(row == i)
continue;
else if(input[num][i][j] >= input[num][row][j])
output[i][j]+=1;
}
}
}
}
...
int main(void)
{
size_t i,j,k,m,n;
printf("Enter the number of parameters: ");
scanf("%zu",&m);
printf("Enter the number of objects: ");
scanf("%zu",&n);
double SVNSFSS[4][n][m];
size_t counts1[n][m] = {{0}};
...
count_gen(n,m,0,SVNSFSS,counts1); // 1st call to the function "count_gen"
...
return 0;
}
Ошибки:
5 99 C:Usersdell pcOneDriveDocumentsC programsSVNSFSS_project.cpp [Error] use of parameter outside function body before ']' token
5 109 C:Usersdell pcOneDriveDocumentsC programsSVNSFSS_project.cpp [Error] use of parameter outside function body before ']' token
5 110 C:Usersdell pcOneDriveDocumentsC programsSVNSFSS_project.cpp [Error] expected ')' before ',' token
5 111 C:Usersdell pcOneDriveDocumentsC programsSVNSFSS_project.cpp [Error] expected unqualified-id before 'double'
Итак, я получил ошибки в строке 3 (в соответствии с кодом выше), и он пометил второе измерение, а именно rowbound
аргумента функции double input[][rowbound][colbound]
, как ошибочное.
Я как-то не знаю, как решить проблему! Пожалуйста, предложите, что мне делать.
2 ответа
Похоже, вы компилируете этот код как C++, а не C (исходя из суффикса имени файла .cpp
).
C++ не поддерживает массивы переменной длины, где размер массива можно указать с помощью переменной времени выполнения или параметра функции; вы должны использовать постоянное выражение для размеров ваших массивов. Простое объявление параметров как const
не делает их постоянными выражениями.
Убедитесь, что вы компилируете этот код как C, а не C++, и вы больше не должны получать эту конкретную ошибку.
0
John Bode
18 Июл 2022 в 18:40
Ошибка, которую вы опубликовали, [Error] use of parameter outside function body before ']' token
, точно говорит вам, что не так. Вы не можете использовать параметр функции в объявлении массива переменной длины в C++. Однако вы можете сделать это в C. См. этот ответ: https://stackoverflow.com/a/25552114/2391458
Если вы пытаетесь принудительно/принудительно установить определенный размер измерения в массивах input
и output
в сигнатуре вашей функции и хотите использовать C++, помните, что параметры, объявленные с типом массива, распадаются на тип указателя.
См. этот ответ: https://stackoverflow.com/a/2276409/2391458 для получения дополнительной информации.
0
FCo
18 Июл 2022 в 18:44