带数组的指针:char * getCharacterAddress(char array [] [arraySize],int row,int column):

时间:2018-06-10 23:58:59

标签: c++ arrays function pointers implementation

我只是在尝试填充function.h中的空实现,但我不明白该怎么做。

在main.cpp测试中,我有以下内容:

TEST_CASE("Testing getCharacterAddress()"){
const unsigned int rows = 5;
const unsigned int columns = 5;

char first[rows][columns] = {
    {'f', 'i', 'r', 's', 't'},
    {'s', 'e', 'c', 'o', 'n'},
    {'t', 'h', 'i', 'r', 'd'},
    {'f', 'o', 'u', 'r', 't'},
    {'f', 'i', 'f', 't', 'h'}
};

for (int i = 0; i < 5; i++){
    for(int j = 0; j < 5; j++){
        void* address = getCharacterAddress(first, i, j);
        INFO("Testing Address: " << address << " to contain: " << first[i][j]);
        REQUIRE(*(char*)address == first[i][j]);
    }
}

}

现在在function.h中我有以下功能:

char * getCharacterAddress(char(* array)[arraySize],int row,int column)

我知道该函数采用2D数组,行和列,但我不知道如何获取特定行和col组合的地址值。

请帮帮我,谢谢!! :)

2 个答案:

答案 0 :(得分:0)

要在c ++中获取变量的地址,请使用&符号&。例如,考虑

int a = 1;
int* b = &a;

b是一个指针,因为它指向a(其值为a的地址)。

同样,您的函数的实现看起来像

char* getCharacterAddress(char arr[rows][columns], int row, int col){
    return &arr[row][col];  // return the adress of the specified char
}

答案 1 :(得分:0)

你想要一个二维数组的条目的地址,对吗?

有一个地址运算符&来检索对象的地址:

char* getCharacterAddress(char array[][5], size_t i, size_t j) { 
    return & array[i][j];
}