0

Hey everyone!!


I am having trouble printing the whole of a multidimensional char array.

#include <iostream>

using namespace std;



int main(){
    
 char array [5][10] = {"---------",
                       "|       |",
                       "|       |",
                       "---------"};  
    
    
    cout << array << endl;
    
    system ("pause");
    return 0;
}

It just gives me random numbers and letters. (I understand that these are "gaps" in memory).

I have been all over google...

PLEASE HELP!!
Thank you sooo much in advance!

Sincerely,

Gernicha

4
Contributors
5
Replies
6
Views
5 Years
Discussion Span
Last Post by Gernicha
0

i would use a nested for loop (for accessing row and column) of a 2-Dimensional array.

>> It just gives me random numbers and letters. (I understand that these are "gaps" in memory).
No. Its the base address of the array (printed by statement on line 15 of your program. (using name of array gives you the base address of the array, i.e. address of its first element)

0

That's because an array is nothing but a pointer to the start of a memory block, so

cout << array << endl;

will print the memory address of the start of your array.

To print the whole array you should iterate over the 'rows' (first index) and print each array these rows define.
(Note: this still sends a pointer to the cout but since this is just a char * it will print all the chars in that bit of memory.)

Also, this explanation isn't perfect but it should at least make you see what's happening and why.

0

Can you give me an example of syntax?

Thanks for your reply!

0

use nested for loops

for( int i = 0; i < 5; i++ )
{
    for( int j = 0; j < 10; j++ )
        cout << array[i][j];
    cout << "\n";
}

just like that :) that way you cover each element in every row and column :)

Edited by Nick Evan: Fixed formatting

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.