문제

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