Home > Backend Development > C++ > body text

How to Simulate Jagged Arrays in C and C ?

DDD
Release: 2024-11-06 04:54:02
Original
479 people have browsed it

How to Simulate Jagged Arrays in C and C  ?

Jagged Arrays in C and C

One may come across the term "jagged array" in discussions about programming languages. However, this concept is not inherently supported in C or C . Jagged arrays refer to an array where each element can be a varying-length array.

In the given code example, an attempt is made to declare a jagged array using the following syntax:

<code class="c">int jagged[][] = { {0,1}, {1,2,3} };</code>
Copy after login

However, C throws an error when compiling, indicating that all dimensions except the first must have bounds specified. This is because C requires arrays to have fixed sizes at compile time.

To simulate jagged arrays in C/C , an approach commonly employed is to utilize an array of pointers. Each pointer in this array points to a dynamically allocated block of memory where elements of a jagged array can be stored.

Example in C:

<code class="c">#include <stdlib.h>

int main() {
    // Initialize array of pointers
    int *jagged[5];

    // Allocate memory for each pointer and set array values
    jagged[0] = malloc(sizeof(int) * 2);
    *(jagged[0]) = 0;
    *(jagged[0] + 1) = 1;

    jagged[1] = malloc(sizeof(int) * 3);
    *(jagged[1]) = 1;
    *(jagged[1] + 1) = 2;
    *(jagged[1] + 2) = 3;

    // Use the jagged array
    // ...

    // Deallocate memory
    free(jagged[0]);
    free(jagged[1]);

    return 0;
}</code>
Copy after login

The above is the detailed content of How to Simulate Jagged Arrays in C and 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!