Click here to Skip to main content
14,773,758 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hello everybody. hope you are safe.
i am trying to write such a code:
char * ARR = new char[3][3];
ARR[3][3]={92,124,47,196,254,196,47,124,92};

but it returns error.
the number inside are not integer as they look; they are character ascii code.
even using a new pointer with more than 1 dimension it messes up.
what syntax should i use?
thanks

What I have tried:

just usin 1 dimension a time
however is not i m looking for.
populate multiple dimension in one line save me coding.
Posted
Updated 30-Nov-20 0:10am

Why allocate that? It can live on the stack if you want it to because it is nine bytes. This :
const char arr[3][3] =
{
      {  92, 124,  47 }
    , { 196, 254, 196 }
    , {  47, 124,  92 }
};
will work.

If you really have to allocate it, you might find it easier understand if you define a type for it.
const int SmallArraySize = 3;
typedef char smallArray[ SmallArraySize ];

const int LargeArraySize = 3;
smallArray * arr = new smallArray[ LargeArraySize ];
and you can still access it as arr[x][y].
   
Comments
CPallini 30-Nov-20 2:11am
   
5.
Try:
char ARR[3][3] = {{92,124,47},{196,254,196},{47,124,92}};
   
As others already pointed out, you don't need to dynamically allocate memory, you might use the stack, instead.
With C++ you have more options, you could, for instance, use a std::vector or a std::array.
Try
#include <iostream>
#include <vector>
#include <array>
using namespace std;

int main()
{
  // using a vector
  vector < vector < unsigned char > > v{{92, 124, 47}, {196, 254, 196}, {47,124,92}};
  cout << static_cast<unsigned>(v[1][2]) << endl;

  // using an array
  array< array< unsigned char , 3 >, 3> a{{{{92, 124, 47}}, {{196, 254, 196}}, {{47,124,92}}}};
  cout << static_cast<unsigned>(a[1][2]) << endl;
}
   
If you absolutely need to allocate the array on the stack you can do the following
char (*ARR)[3] = new( char [5][3] { { 192, 124, 47 },
                                     {196, 254, 196},
                                     {47, 124, 92},
                                     {154, 129, 197},
                                     {36, 49, 124} };

Note that we use char (*ARR)[3] to declare an pointer to array[3] of char. If we use char *ARR[3], we've declared an array[3] of pointer to char, and can't use the brace initialization.
   
thanks for this plenty of solutions.
i keep being surprised on how many variants this language has.
just moving a font along the string code can completely change how is ment to be and the code being executed. i wonder how can expert programmer hold in memory all these alternatives.
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900