There is a question about saving the array after entering the c language file.

Asked 2 years ago, Updated 2 years ago, 140 views

Hello, I am a student who is learning programming in C language these days. One of the things you have to do is open the data.txt file and save it as an array and solve the problem using those arrays, but I don't know how to open the file and save it as an array. The data.txt file is now

-2, 3, 4

1, -3, -4

It's saved like this. To open it up

FILE *fp;
  fp=fopen("data.txt", "r");
    for (ch = getc(fp); ch != EOF; ch = getc(fp)) 
        if (ch == '\n') 
            r = r + 1; 
    c = r + 1;

I think I opened the file like this and got the total number of rows and rows after that, but I don't know if this is right. After that, I'm going to save it in an array, but if I use malloc, I think I can get the value of each array, so I'm going to use it, how do I do it?

 int **arr = (int **)malloc(r * sizeof(int *));
  for (i = 0; i < r; i++) {
    arr[i] = (int *)malloc(c * sizeof(int));
  }
 for(i = 0; i < r; i++) {
   for(j = 0; j < c; j++) {
     fscanf(fp, "%d", &arr[i][j]);
       printf("%d\n",arr[i][j]); 
   }
 }

I thought it would be saved if I did, but it doesn't Please help me As the final goal, if you do printf("%d", mat[0][0]), you can get -2.<

c array malloc

2022-09-21 18:35

1 Answers

 I wrote it assuming that the number of columns is 3
If the number of columns varies from line to line, we need to modify it a little bit
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define COL 3

main(){ 
        FILE *fp = fopen("data.txt", "rb")?: puts("fopen error");
        char *buf, *iter = buf;
        int (*mat)[COL] = malloc(BUFSIZ * COL * sizeof(int));

        for(int cnt=0; (*iter = fgetc(fp)) != EOF; iter++){
                if(strchr(",\n", *iter)){
                        mat[cnt / COL][cnt++ % COL]= atoi(buf);
                        buf = iter + 1;
                }
        }

        printf("%d", mat[0][0]);

        free(mat);
        fclose(fp);
}

The reason why there is an error when executing C code on the web with the
 code execution button is because
It's probably because you can't create and access the data.txt file We'll do well with the local C compiler


2022-09-21 18:35

If you have any answers or tips

Popular Tags
python x 4647
android x 1593
java x 1494
javascript x 1427
c x 927
c++ x 878
ruby-on-rails x 696
php x 692
python3 x 685
html x 656

© 2024 OneMinuteCode. All rights reserved.