简体   繁体   中英

Creating a Dynamic 2-D Char array in c

I am having the following 2 lines in a text file

4

oxd||987||ius||jjk

I want to store the data in a 2-dim char array. The first line is basically representing the number of rows in array and let suppose the columns in the array are fixed to 3. The data will be splitted on the basis of || .

So how can i declare such a dynamic array.

In C, it's no problem - you have VLAs. Something like:

fgets(buf, sizeof buf, stdin);
int rows = strtol(buf, NULL, 0);

To get the number of rows, and then:

char array[rows][3];

And you're done. Here's a complete (well, no error checking) example demonstrating how to use it given your input:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void)
{
    char buf[100];
    fgets(buf, sizeof buf, stdin);

    int rows = strtol(buf, NULL, 0);
    char array[rows][3];

    fgets(buf, sizeof buf, stdin);

    char *s = strtok(buf, "|");
    for (int i = 0; i < rows; i++)
    {
        strncpy(array[i], s, 3);
        s = strtok(NULL, "|");
    }

    for (int i = 0; i < rows; i++)
    {
        printf("%.3s\n", array[i]);
    }

    return 0;
}

Example run & output:

$ make example
cc     example.c   -o example
$ ./example < input
oxd
987
ius
jjk

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM