Store pointer to 2d array [duplicate] - c++

This question already has answers here:
How do I declare a 2d array in C++ using new?
(29 answers)
Closed 8 years ago.
So I have a private member in the class Map:
char **_map;
I then try to initialize the pointer array to a two dimensional char array like this:
std::vector<std::string> contents = StringUtils::split(_mapInfo.getContents(), ' ');
const int x = StringUtils::toInt(contents.at(0));
const int y = StringUtils::toInt(contents.at(1));
_map = new char[x][y];
Basically the contents vector contains two strings, which I then convert into integers. I then try to initialize the map array but I receive this error:
Error 1 error C2540: non-constant expression as array bound
And this:
Error 2 error C2440: '=' : cannot convert from 'char (*)[1]' to 'char **'
And finally this:
3 IntelliSense: expression must have a constant value
The last error references the variable y
Can anyone explain what is happening and how I can fix it?

The initialization of 2d array is as following;
char **_map;
_map = new char*[rowsize];
for(int row = 0; row < rowsize; ++row)
{
_map[row] = new char[columnsize]
}

Related

C++ cannot assign to return value because function 'operator []' returns a const value [duplicate]

This question already has answers here:
C++ std::set update is tedious: I can't change an element in place
(7 answers)
std::set iterator automatically const [duplicate]
(2 answers)
Closed 1 year ago.
Hi every one I'm new to C++, and practicing it by leetcode.
Today when I was trying lc127, this error confused me. This error comes from one ranged for statement, where variable first is of the type unordered_set. And if I removed the reference mark&, then it works all right.
The most minimal reproducible example is like:
unordered_set<string> first{ beginWord }, last{ endWord };
int i = 0, j = 'a';
for (auto& word : first) {
word[i] = j;//error here
}
And the error shows:
Line 17: Char 33: error: cannot assign to return value because function 'operator[]' returns a const value
word[i] = j;
~~~~~~~ ^
/usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/basic_string.h:1045:7: note: function 'operator[]' which returns const-qualified type 'std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>>::const_reference' (aka 'const char &') declared here
const_reference
^~~~~~~~~~~~~~~
My question is that why the former version is wrong? To my understanding, if I want to change the value in a ranged for statement, then I should use a & to ensure that I changed the value?
Full code link:Full code is here
Thank you in advance!

C++: Type of multidimensional array with `variable` size

I can run this
int a = 5;
auto foo = new int [a][4][4];
But when I try this:
int a = 5;
int * foo[4][4];
foo = new int [a][4][4];
I get the error
error: incompatible types in assignment of ‘int (*)[4][4]’ to ‘int* [4][4]’
Question
What type do I have to specify for foo?
Edit:
The goal is to have one single chunk of memory, not an array of pointers.
The error message is a little confusing because it does not state the variable name.
This works:
int a = 5;
int (*foo)[4][4];
foo = new int [a][4][4];
As #john correctly identified:
You're confused between a 2D array of pointers (that's what you wrote) and a pointer to a 2D array (that's what you want).
So what's the difference between pointer to an array and array of pointers. The correct syntax to define a pointer to an array (what you tried to do):
data_type (*var_name)[array_size];
But this defines an array of pointers (what you actually did):
data_type *var_name[array_size];
#OP in your own answer you already found out what the correct type should be – a pointer to an array int (*foo)[4][4], but I thought a little more explanation is also helpful.

Compiler showing warning during compilation of the following code [duplicate]

This question already has answers here:
warning: format ‘%s’ expects type ‘char *’, but argument 2 has type ‘char (*)’
(3 answers)
Closed 5 years ago.
#include<stdio.h>
int main()
{
char str[6][50] ; // a 2d character array
int i ;
for(i = 0 ; i < 6 ; i++)
{
scanf("%s",(str+i)) ; // in here the warning was shown
}
return 0 ;
}`
During Output :-
scanf() is showing warning on compilation - warning: format ‘%s’ expects argument of type ‘char ’, but argument 2 has type ‘char ()[50]’ [-Wformat=]
Remember that arrays naturally decays to pointers to their first element? That means str by itself is treated as a pointer. With str + i you are doing pointer arithmetic, the result of which is another pointer (to the i:th element in this case). The type of that pointer is a pointer to an array, char (*)[50], it's not the array itself.
What you need to do is to dereference the pointer: *(str + i). Or as it's the same, str[i].
It seems like you are trying to access each element of str in turn. To do this use scanf("%s",str[i]); (as per usr's comment).

error C2440: '=' : cannot convert from 'int *' to 'int **'

#ifndef _grid_h
#define _grid_h
#include<string>
using namespace std;
template<typename T>
class grid{
T** main;
public:
grid<T>(){}
grid<T>(int col, int row){
main = new T[col]; //<-this line gives me error C2440:
//'=' : cannot convert from 'int *' to 'int **'
for(int i =0;i<col;i++)
main[i]=new T[row];
}
};
#endif
I want to create my own version of the Grid class. Basically I want to save the information in a 2 dimensional array of T. I think this is the most efficient way to do it. Now How can I get around this error?
It would need to be
main = new T*[col];
Because main is an array of pointers to T. But there are better ways to create a two-dimensional array, for example
std::vector<std::vector<T>> main(col, std::vector<T>(row));
Allocate an array of correct type: use main = new T*[col]; instead of main = new T[col];.
The answer is in your last code line:
main[i]=new T[row];
For that to work, main[i] needs to be a pointer. But you tried to create main as a new T[col] - an array of Ts. It needs to be an array of pointers-to-T.
main = new T*[col]; // Create an array of pointers

Cannot assign integer to dynamically allocated 2D array

I have created a 2D-array in following way:
int** map_array = (int**)malloc(sizeof(yy_value*xx_value));
When i try to assign a value on a position:
map_array[y*xx_value+x] = 5;
I get following error:
Assigning to 'int *' from incompatible type 'int'
What am i doing wrong here?
Change:
int** map_array = (int**)malloc(sizeof(yy_value*xx_value));
to:
int* map_array = (int*)malloc(yy_value*xx_value*sizeof(map_array[0]));
Explanation: you're allocating a "flattened" 2D array here, where you calculate your own 1D index rather than an actual 2D array. Also the size passed to malloc was incorrect.
Note that you should probably not be using malloc in a C++ program without a good reason.
you can alternatively use a 2D array as:
int **map_array = (int**)malloc(xx_value*sizeof(int*))
for (i = 0; i < xx_value; i++) {
map_array[i] = (int*)malloc(yy_value*sizeof(int))
}
and access elements using:
map_array[x][y] = 5;