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
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top