Ravi Rikhi
Ravi Rikhi

Reputation: 1

error : no match for 'operator[]'

I am solving a problem in which I m trying to pass address a 2-D array of a structure and trying to manipulate it but, whenever I use [] operator to access the array elements , I get a compile time error:

no match for 'operator[]'

in my codeblocks IDE.

#include <iostream>

using namespace std;

typedef struct mat
{
   int data;
   int flag;
} cell;

int mat(cell *);

int main()
{
    int m,n;
    cin>>m>>n;
    cell game[n][m];
    cout<<"The length of matrix is "<<mat(&game[0][0]);
}

int mat(cell *arr)
{
    return (sizeof(arr[0])/sizeof(arr[0][0]));
}

Upvotes: 0

Views: 1318

Answers (3)

tep
tep

Reputation: 833

Two things:

  1. Your function takes a pointer to cell but since you're treating it like a 2D array, you should probably change your signature to either accept a cell ** arr or a cell arr[m][] where m is the (fixed) size of the array and must be specified. Note that these data structures have fundamentally different representations in memory - they just have the same [][] syntax for accessing elements.

  2. You can't use the sizeof function to determine the length of an array if you pass it as a pointer to an elem. You will need to pass the dimensions along with your array, like this:

int mat(cell **arr, int m, int n);

Upvotes: 1

n. m. could be an AI
n. m. could be an AI

Reputation: 119877

cell game[n][m];

This is not legal C++. You are using a compiler-specific extension. At this point I advise you against using any compiler-specific extensions. Use standard C++ only. In standard C++ there are no Variable Length Arrays. Don't use arrays in your C++ programs. To get proper variable length array functionality. You should use std::vector instead, like this:

std::vector<std::vector<cell>> game;

Further,

&game[0][0]

is not an address of a 2D array. This is an address of the first element in the array. It contains no information about the number of elements. It is lost forever. You cannot pass it to some function and expect the size of the array to be recovered. To get proper array functionality with a built-in size function, use std::vector.

Last but not least,

(sizeof(arr[0])/sizeof(arr[0][0]));

arr is a cell*. arr[0] is a cell. arr[0][0] is invalid because a cell is neither an array not a pointer, nor it has a custom [] operator defined. In any case you cannot use sizeof to recover the number of elements in the array from a pointer to its first element. To get proper array functionality with a built-in size function, use std::vector.

Upvotes: 2

kfroemming
kfroemming

Reputation: 321

The definition being given basically says that your class doesn't define the operator [], meaning you can't use the syntax you are trying to use.

Upvotes: 0

Related Questions