Error use of parameter outside function body before token

  • 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?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
using namespace std;

int fillArrayPointer(const int R, const int C, int a[R][C]);

int main() 
{
  //creating 2D array
  const int R=2;
  const int C=2;
  int A[R][C] = {{2,9}, {6,4}};

  fillArrayPointer(R, C, A[][C]);
}

int fillArrayPointer(const int R, const int C, int a[R][C])
{
//creating 1D runtime array and putting all values from 2D array in it
  int* B= new int [R*C];
  for (int i=0; i<R; i++)
  {
    for (int j=0; j<C; j++)
    {
      int a=0;
      B[a]=A[i][j];
      a++;
    }
  }
}

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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
using namespace std;

int fillArrayPointer(const int R, const int C, int a[R][C]);

int main()
{
  //creating 2D array
  const int R=2;
  const int C=2;
  int A[R][C] = {{2,9}, {6,4}};

  fillArrayPointer(R, C, A[][C]);
}

int fillArrayPointer(const int R, const int C, int a[R][C])
{
  //creating 1D runtime array and putting all values from 2D array in it
  int* B= new int [R*C];
  for (int i=0; i<R; i++)
  {
    for (int j=0; j<C; j++)
    {
      int a=0;
      B[a]=A[R][C];
      a++;
    }
  }
}

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).

1
2
constexpr int C {2}; // global constant
int fillArrayPointer( int rows, int a[][C]);
1
2
3
  const int R=2;
  int A[R][C] = {{2,9}, {6,4}};
  fillArrayPointer( R, C, A[][C] );

error: expected primary-expression before ']' token
1
2
3
4
5
6
7
8
A       // is the whole array
A[1]    // is the second row of the array. An array of int
A[1][0] // is one int

// hence:
  constexpr int R {2};
  int A[R][C] {{2,9}, {6,4}};
  fillArrayPointer( R, A );
1
2
3
4
5
6
7
8
9
10
11
12
13
14
int fillArrayPointer( int rows, int a[][C] )
{
  //creating 1D runtime array and putting all values from 2D array in it
  int* B= new int [rows*C];
  for (int i=0; i<rows; i++)
  {
    for (int j=0; j<C; j++)
    {
      int a=0;
      B[a]=A[rows][C];
      a++;
    }
  }
}

 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:

1
2
3
4
for (int j=0; j<C; j++)
{
  B[0] = A[R][C];
}

* Wait, the R and C are effectively constants. The loop is:

1
2
3
4
for (int j=0; j<C; j++)
{
  B[0] = A[2][2];
}

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?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>

template<size_t R, size_t C>
int* fillArrayPointer(const int (&a)[R][C])
{
	//creating 1D runtime array and putting all values from 2D array in it
	int *B {new int[R * C]}, *D {B};

	for (int i = 0; i < R; ++i)
		for (int j = 0; j < C; ++j)
			*D++ = a[i][j];

	return B;
}

int main()
{
	const int R {2};
	const int C {2};
	const int A[R][C] {{2,9}, {6,4}};
	const int* const D {fillArrayPointer(A)};

	for (size_t i = 0; i < R * C; ++i)
		std::cout << D[i] << "  ";

	std::cout << 'n';

	delete[] D;
}

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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <cstring>

template<size_t R, size_t C>
int* fillArrayPointer(const int (&a)[R][C])
{
	//creating 1D runtime array and putting all values from 2D array in it
	return reinterpret_cast<int*>(memcpy(new int[R * C], &a, R * C * sizeof(int)));
}

int main()
{
	const int R {2};
	const int C {2};
	const int A[R][C] {{2,9}, {6,4}};
	const int* const D {fillArrayPointer(A)};

	for (size_t i = 0; i < R * C; ++i)
		std::cout << D[i] << "  ";

	std::cout << 'n';

	delete[] D;
}

However, rather than dealing with raw-pointers, a better C++ way would be to use a managed pointer.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <cstring>
#include <memory>

template<size_t R, size_t C>
auto fillArrayPointer(const int (&a)[R][C])
{
	//creating 1D runtime array and putting all values from 2D array in it
	return std::unique_ptr<int[]> (reinterpret_cast<int*>(memcpy(new int[R * C], &a, R * C * sizeof(int))));
}

int main()
{
	const int R {2};
	const int C {2};
	const int A[R][C] {{2,9}, {6,4}};
	auto D {fillArrayPointer(A)};

	for (size_t i = 0; i < R * C; ++i)
		std::cout << D[i] << "  ";

	std::cout << 'n';
}

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

Понравилась статья? Поделить с друзьями:
  • Error uploading file перевод
  • Error uploading file rockstar support
  • Error upload reason ffmpeg2opus fail
  • Error uplaycrashreporter cpp 262
  • Error uplay pc is not currently installed your game needs access