batking28
batking28

Reputation: 1

Printing out 2D array from function C++

Ive been trying this for hours no and have made no progress, the programme should create a 2D array in the function of a 16 by 16 grid of x's and then in the main programme i should be able to print this grid on the console but when run i get no result, any help would be apreciated (newbie)

#include <iostream>
#include <cstdlib>

char **create2DArray();  //function prototype 

#define WIDTH 16 
#define HEIGHT 16 

char** myArray;  //global array 


char **create2DArray(){ 
    int i,j; 
    char **array = (char **) malloc(sizeof(char *) * WIDTH); 

    for(i=0; i<WIDTH; i++) 
        array[i] = (char *) malloc(sizeof(char) * HEIGHT);  

        for(i=0; i<WIDTH; i++)              
            for(j=0; j<HEIGHT; j++)             
                array[i][j] = 'x'; 
    return array; 
} 

int main(int argc, char** argv) {

    char **create2DArray(); 
    myArray = create2DArray(); 
    void printArray(char** array); 

    return 0;
}

Upvotes: 0

Views: 84

Answers (1)

Praneeth Peiris
Praneeth Peiris

Reputation: 2088

You have to implement printArray function.

void printArray(char** array)
{
    for(int i=0; i<sizeof(array); i++)
    {
        for(int j=0; j<sizeof(array[i]); j++)
        {
            std:: cout << array[i][j] << " ";
        }
        std::cout << std::endl;
    }
}

Then call it in the main, and add void printArray(char** array) as a function prototype.

printArray(myArray);

Upvotes: 1

Related Questions