1

I have a dynamically allocated 2d array and would like to loop through it with pointer arithmetic because I won't know the number of rows and number of cols before runtime.

I know how to do this with a 1d array:

int *arr = new int[size];

and to loop through it:

for (int *i = arr; i < arr + arr.size(); i++){
    *i = 20; //sets all elements to 20
}

However, it's at the 2d level that I get stuck. Here's what I have so far:

int **arr = new int *[row];
for(int i = 0; i<row; i++)
    arr[i] = new int[col];

To loop through all values:

for(int **i=arr; i < arr + row; i++){
    for(int *j=*i; j < j + col; j++){
        *j = 20; // set all values to 20
    }
}

The second loop is obviously incorrect, I just don't know what else to try.

1 Answer 1

3

You should do the same thing to j as you did to i.

for(int **i=arr; i < arr + row; i++){
    for(int *j=*i; j < *i + col; j++){
        *j = 20; // set all values to 20
    }
}
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.