Home  >  Article  >  Backend Development  >  How to Simulate Jagged Arrays in C and C ?

How to Simulate Jagged Arrays in C and C ?

DDD
DDDOriginal
2024-11-06 04:54:02480browse

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>

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>

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!

Statement:
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