0

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 ?

1
  • Well, let's start with the basics. You cannot return cords in getPosition, as this is a local variable who's memory is not valid when the function returns. If you want to return an array from that method, you have to allocate it (malloc). Commented Nov 22, 2015 at 15:32

1 Answer 1

1

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.

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

1 Comment

Thanks :D !!! I forgot about that, it was only a local variable, but still it worked somehow... Anyway, your solution is great, it is exactly what I was looking for. :)

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.