首页 文章

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

提问于
浏览
0

我只是在尝试填充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数组,行和列,但我不知道如何获取特定行和列组合的地址值 .

请帮帮我,谢谢!! :)

2 回答

  • 0

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

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

    char* getCharacterAddress(char array[][5], size_t i, size_t j) { 
        return & array[i][j];
    }
    
  • 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
    }
    

相关问题