Allocating data arrays in C++

lets say that I have a two dimensional array:

char myarray[10][10];

and my process of taking in values from an input file is this:

for(i=0;x<2;i++)  // 2 is the amount of rows in the array
{ 
input>>myarray[x];
}

now when I display my array my output is this:
why
hello

To make this work dynamically I am trying to go about doing it this way:

char* a = new char[max];
for(i=0;x<2;i++)  // 2 is the amount of rows in the array
{ 
input>>myarray[x];
}

now when I try to output my input, I go about doing it this way:

for(i=0;x<2;i++)
{
cout<<myarray[x];
}

I am currently having trouble with pointers...

Your previously two-dimensional array has become a one-dimensional array, since a "char *" just points to one list of characters. And in dereferencing it, you're telling cin to read in a single character.

Try

char **strings=new char *[2];

for(n=0; n<2; n++)
{
       strings[n]=new char[max];
       cin >> strings[n];
}

ohhhh so you need 2 **'s to reference a double dimensional array?

Well, this isn't precisely a two-dimensional array, either. It's a one-dimensional array, but it's an array of pointers. So you can allocate memory and keep a pointer to that memory in each slot. A single 'char *' can't do that since it holds characters, not pointers.

What I am having trouble with right now is that I cannot take multiple lines of single words and dynamically take them from the input file and display it.

However, I can do the easier part which is take the averages of the data ( which is stored in a single dimensional INT array ) and dynamically allocate that data.

So to sum things up, I am having trouble working with 2d arrays ( int and char ).
While dynamically allocating the input ( I understand 2d arrays but not the dynamically allocating part ).

Further explanation.

error C2440: '=' : cannot convert from 'char (*)[12]' to 'PointerToChar'

UPDATE

I am now only stuck on dynamically allocating the 2 words on the right of my data.

Please post your code.

typedef char* characterptr;
characterptr *stuff=new characterptr;
for(x=0; x < 2; x++) 
{ 
	 
	input >>stuff[x];}

Is that correct so far?

Then to display it,

for(y=0;y<lengthofvar;y++){
	cout<<stuff[x];
	}

I don't get errors either, just a crash.

---------- Post updated at 07:01 PM ---------- Previous update was at 06:21 PM ----------

taking a 2 hour break, but ill be back to see if you answered my question!

That's not correct, I suggest you try what I posted instead.

You're just allocating pointers. A pointer to nothing can't hold anything. You need to allocate memory for them to point to, too, like I did.

1 Like

Thank you very much! you helped me alot!