Home > Backend Development > C++ > body text

How to Convert a 2D Array to a Pointer-to-Pointer in C ?

Linda Hamilton
Release: 2024-11-12 10:07:01
Original
778 people have browsed it

How to Convert a 2D Array to a Pointer-to-Pointer in C  ?

Converting a 2D Array to a Pointer-to-Pointer

Consider the following scenario:

Activity solution[a][b];
// ...
Activity **mother = solution;
Copy after login

In this situation, you may desire to convert a 2D object array into a pointer-to-pointer. However, direct conversion is not possible due to the incompatibility of types.

Introducing an Intermediate Array

To bridge the gap, introduce an intermediate "row index" array:

Activity solution[a][b];

Activity *solution_rows[a] = { solution[0], solution[1] /* and so on */ };

Activity **mother = solution_rows;
Copy after login

This allows you to access elements in the following manner:

mother[i][j] = solution[i][j]
Copy after login

Understanding the Conversion

solution[i] is a pointer to the i-th row of the 2D array. solution_rows is an array of these row pointers. Therefore, solution_rows[i] is equivalent to solution[i].

When you assign solution_rows to mother, you effectively create a pointer-to-pointer that points to the first elements of each row in solution.

The above is the detailed content of How to Convert a 2D Array to a Pointer-to-Pointer in C ?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template