0

i'm trying to pass a 2D char array into a function declared in a header file.

//Proj1Aux.h

#ifndef PROJ1AUX_H
#define PROJ1AUX_H

void makeBoard(char (*myBoard)[10], int boardSize);
void printBoard(char (*myBoard)[10], int boardSize);

#endif

I defined the functions as follows:

//Proj1Aux.cpp

#include <iostream>
#include "Proj1Aux.h"

using namespace std;

void makeBoard(char (*myBoard)[10], int boardSize)
{
    //code
}

void printBoard(char (*myBoard)[10], int boardSize){

    //code
}

And then in my main function in another .cpp file:

//Proj1.cpp


#include <iostream>
#include <cstdlib>
#include "Proj1Aux.cpp"

using namespace std;

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

    //code...
    //more code...

    char board[10][10];
    makeBoard(board, boardSize);
    printBoard(board, boardSize);

}

I'm a beginner at C++, and I dont have a firm grasp on pointers, or even header files. I tried passing in the 2D array without any pointers, but the compiler gave me an error:

invalid conversion from 'const char*' to 'char'

So i tried putting in the pointers as listed above, and I get the same error

What do I do? can anyone go through my code and tell me exactly what's wrong?

2
  • Don't include .cpp files in other .cpp files until you have a very, very solid understanding of header files. That's an advanced technique that will only get you into trouble for now. Commented Mar 8, 2014 at 17:49
  • Can you paste the exact error you get and indicate which line you get it on? Commented Mar 8, 2014 at 17:56

1 Answer 1

1

Your code doesn't agree with itself.

char board[10][10];

This says board is a 2D array, 10 by 10.

makeBoard(board, boardSize);

This passes board to makeBoard, which will only work if makeBoard's first parameter is compatible with a 10 by 10, 2D array.

void makeBoard(char (*myBoard)[10], int boardSize)

But this says the first parameter to makeBoard is a pointer to a 1D array. That's nothing like a 2D array -- they're completely incompatible. Arrays are compatible with pointers to their first elements. So a pointer to a 1D array has two levels of indirection -- the pointer leads you to a 1D array, which decays into a pointer to the first element. A 2D array has one level of indirection -- the array decays into a pointer to its first element.

So, which is it? Is the parameter a pointer to the contents, or a pointer to a pointer to the contents?

Why not just use std::vector instead of arrays?

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.