简体   繁体   中英

Assigning array to array by having pointer to its first element

Here is my function that in my belief (I am still trying to get used to pointers) returns a pointer to the first element of the array named cords :

int* getPosition( char arr[][5], char letter ) {
    int cords[2];
    for ( int y = 0; y < 5; y++ ) {
        for ( int x = 0; x < 5; x++ ) {
            if ( arr[y][x] == letter ) {
                cords[0] = x;
                cords[1] = y;
            }
        }
    }
    return cords;
}

Here's my second function:

string scrambling( char arr[][5], vector<string> *pairs ) {
    string encrypted;
    int firstCords[2];
    ...
}

I want to somehow assign values from the array "cords" from the function getPosition to the array firstCords in the function scrambling() .

My temporary solution was:

firstCords[0] = getPosition( arr, (*pairs)[i][0] )[0];
firstCords[1] = getPosition( arr, (*pairs)[i][0] )[1];

And it's the only solution I came up with that actually works. I'm really keen on getting to know a way, how I can achieve this in one line ?

cords is a local variable, so using it beyond the end of the function it has been defined in is undefined behavior .

An easy way would be to pass a pointer to firstCords to getPosition and let getPosition fill it in. Declare getPosition like this:

void getPosition(int cords[2], char arr[][5], char letter);

And call it like that in scrambling :

getPosition(firstCords, arr, (*pairs)[i][0]);

Note that int cords[2] as a formal parameter to getPosition is not an array but a pointer .
Here is a nice (well, depends on how you define it) post on the Linux Kernel Mailing List by Linus Torvalds regarding some programmer who made a similar mistake.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM